Get “data from collection b not in collection a” in a MongoDB shell query

后端 未结 4 2004
执笔经年
执笔经年 2020-12-23 14:06

I have two MongoDB collections that share a common _id. Using the mongo shell, I want to find all documents in one collection that do not have a matching _id in the other co

4条回答
  •  太阳男子
    2020-12-23 14:34

    In mongo 3.2 the following code seems to work

    db.collectionb.aggregate([
        {
          $lookup:
            {
              from: "collectiona",
              localField: "collectionb_fk",
              foreignField: "collectiona_fk",
              as: "matched_docs"
            }
       },
       {
          $match: { "matched_docs": { $eq: [] } }
       }
    ]);
    

    based on this https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#use-lookup-with-an-array example

提交回复
热议问题