Nasco.Chachev
Nasco.Chachev

Reputation: 676

Querying a document from array inside a collection mongoDB

I'm trying to fetch a data from my MongoDB's collection, I have the following structure:

check JSON structure here.

So basically the thing I want to do for example is to target object with id: 456 FROM events where the top level _id is == 2 and to return only that object.

I've tried aggregate() , findOne() but none of them works the way I want... any help will be appreciated.

Examples I've tried:

db.collectionName.findOne({ _id: '2', events: { $elemMatch: { _id: 456 } }})

I can't change the following structure , because the top level _id is actually userId and I want to fetch all the events for the user with _id: '2' for example.

Upvotes: 1

Views: 36

Answers (1)

mickl
mickl

Reputation: 49995

You can start with filtering by _id to filter out as much as possible. Then you can use $unwind to get single event per document and apply another match for nested _id. In the last step you can use $replaceRoot to get only nested document, try:

Model.aggregate([
    { $match: { _id: "2" } },
    { $unwind: "$events" },
    { $match: { "events._id": "456" } },
    { $replaceRoot: { newRoot: "$events" } } 
])

Outputs:

{ "_id" : "456", "name" : "eventName_1" }

Upvotes: 1

Related Questions