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

后端 未结 4 2011
执笔经年
执笔经年 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:43

    You will have to save the _ids from collection A to not pull them again from collection B, but you can do it using $nin. See Advanced Queries for all of the MongoDB operators.

    Your end query, using the example you gave would look something like:

    db.Test.find({"_id": {"$nin": [ObjectId("4f08a75f306b428fb9d8bb2e"), 
     ObjectId("4f08a766306b428fb9d8bb2f")]}})`
    

    Note that this approach won't scale. If you need a solution that scales, you should be setting a flag in collections A and B indicating if the _id is in the other collection and then query off of that instead.

    Updated for second part:

    The second part is impossible. MongoDB does not support joins or any sort of cross querying between collections in a single query. Querying from one collection, saving the results and then querying from the second is your only choice unless you embed the data in the rows themselves as I mention earlier.

提交回复
热议问题