简体   繁体   中英

mongodb: find all records by condition in other documents

Not sure how to formulate the task correctly in words.

Say there are such documents in a collection:

  {id:1, type: 'added' },
  {id:1, type: 'completed' },
  {id:2, type: 'added' },
  {id:3, type: 'added' },

Find all documents with type added for which doesn't exist records with the same id and completed

So it would find only:

  {id:2, type: 'added' },
  {id:3, type: 'added' },

You can use below aggregation

db.collection.aggregate([
  { "$group": {
    "_id": "$id",
    "types": { "$push": "$type" }
  }},
  { "$match": {
    "types": {
      "$in": ["added"],
      "$nin": ["completed"]
    }
  }}
])

Output

[
  {
    "_id": 3,
    "types": [
      "added"
    ]
  },
  {
    "_id": 2,
    "types": [
      "added"
    ]
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM