Azamat Abdullaev
Azamat Abdullaev

Reputation: 806

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;

Upvotes: 0

Views: 21

Answers (1)

turivishal
turivishal

Reputation: 36114

  • $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

Upvotes: 1

Related Questions