代码之家  ›  专栏  ›  技术社区  ›  GregH

是否可以在MongoDB中执行子查询以返回$nin运算符的数组?

  •  0
  • GregH  · 技术社区  · 7 年前

    我有一个数据集,看起来像:

    {"key": "abc", "val": 1, "status": "np"}
    {"key": "abc", "val": 2, "status": "p"}
    {"key": "def", "val": 3, "status": "np"}
    {"key": "ghi", "val": 4, "status": "np"}
    {"key": "ghi", "val": 5, "status": "p"}
    

    我想要一个查询,该查询返回具有status=“np”的文档,但仅当具有相同键的其他文档的status值不为“p”时才返回。因此,从上述数据集返回的文档将是key=“def”,因为“abc”的值为“np”,但“abc”也有一个值为“p”的文档。key=“ghi”也是如此。我找到了一些接近的方法,但我认为$nin操作符不支持q distinct查询。

    db.test2.find({$and: [{"status":"np"}, {"key": {$nin:[<distinct value query>]]})
    

    如果我对$nin数组中的值进行硬编码,它会起作用:

    db.test2.find({$and: [{"status":"np"}, {"key": {$nin:['abc', 'ghi']}}]})
    

    我只需要能够在方括号内写下一个结果。我可以这样做:

    var res=[];
    res = db.test2.distinct("key", {"status": "p"});
    db.test2.find({$and: [{"status":"np"}, {"key": {$nin:res}}]});
    

    但问题是,在两次查询之间,另一个进程可能会更新文档的“状态”,然后我会得到不一致的数据。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Graciano    7 年前

    试试这个

    db.so.aggregate([
     {$group: {'_id': '$key', 'st': {$push: '$status'}}},
     {$project :{st: 1, '$val':1, '$status':1, 'hasNp':{$in:['np', '$st']}, hasP: {$in:['p', '$st']}}},
     {$match: {hasNp: true, hasP: false}}
    ]);