skip to Main Content

I have the following document structure

{
    _id: ..., 
    topics: [ ... ], 
    posts: [ {id: 1}, {id:2}, {id: 3}]
}

I would like to find all posts that match specific ids. E.g

[2,3]

I have tried this:

db.getCollection("data")
    .find({},{
        posts: {
            $elemMatch: {
                id: {
                    $in: [2, 3]
                    } 
                }
            }
        })

but it only return one post

{
    _id: ..., 
    posts: [ {id: 3} ]
}

I guess another way to go would be to just return all posts and filter then manually. Which one would have a better performance?

2

Answers


  1. Try with below query it should work for you.

    db.getCollection("data")
        .find({
            "posts.id": {
                        $in: [2, 3]
                        } 
            })
    
    Login or Signup to reply.
  2. If you want to achieve it via, MongoDB, you will have to achieve it via an aggregation pipeline, because you want to filter the posts array, which is done via the $filter operator, as suggested in the comments by @turivishal. Try this:

    db.collection.aggregate([
      {
        "$addFields": {
          "posts": {
            "$filter": {
              "input": "$posts",
              "as": "item",
              "cond": {
                "$in": [
                  "$$item.id",
                  [
                    1,
                    2
                  ]
                ]
              }
            }
          }
        }
      }
    ])
    

    Playground link.

    In terms of performance, usually, the filtering at the DB level is better because the operators are optimized as much as possible and also it reduces the data transferred as everything unnecessary is filtered out.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search