2

Query :

db.DEFAULT.find({ "bookStore.books.book.bookId":7501},{"bookStore.books.book.bookId" :1});

Collection :

{
"_id" : ObjectId("5988814feb46972540cebccd"),
"bookStore" : [ 
    {
        "books" : [ 
            {
                "book" : {
                    "bookId" : 7501
                }
            }, 
            {
                "book" : {
                    "bookId" : 7502
                }
            }, 
            {
                "book" : {
                    "bookId" : 7500
                }
            }
        ]
    }
]
}

When I run the query, it displays all the 3 records. Is there anyway only the matching record will be displayed in the results.

1 Answer 1

2

You need $map with $filter since your arrays have more than one level of nestings:

db.collection.aggregate([
    {
        $addFields: {
            bookStore: {
                $map: {
                    input: "$bookStore",
                    as: "bs",
                    in: {
                        books: {
                            $filter: {
                                input: "$$bs.books",
                                as: "b",
                                cond: {
                                    $eq: [ "$$b.book.bookId", 7501 ]
                                }
                            }
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.