简体   繁体   中英

MongoDB filter documents if they have associated children

Let's say we have two collections, users and posts :

{
  "users": [
    {
      "_id": 1,
      "name": "John"
    },
    {
      "_id": 2,
      "name": "Jack"
    },
    {
      "_id": 3,
      "name": "Mike"
    }
  ],
  "posts": [
    {
      "_id": 1,
      "text": "Post 1",
      "userId": 1
    },
    {
      "_id": 2,
      "text": "Post 2",
      "userId": 1
    },
    {
      "_id": 3,
      "text": "Post 3",
      "userId": 2
    }
  ]
}

Now, the question is as follows: How can I write a query to filter out users (using aggregation pipeline or something else) depending on whether they have posts? For example, my query should only return an array of users with _id 1 and 2, not 3. Because, there are no posts with userId: 3 ;

  • $lookup join posts collection
  • $match is return post is not empty
  • $project to remove post field if its not needed
db.users.aggregate([
  {
    "$lookup": {
      "from": "posts",
      "localField": "_id",
      "foreignField": "userId",
      "as": "post"
    }
  },
  { $match: { post: { $ne: [] } } },
  { $project: { post: 0 } }
])

Playground

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