Search code examples
arraysmongodbnode-mongodb-nativedatabase

Querying mongoDB document based on Array element


enter image description here

This is one user's notes. I want to query and get only the notes of this use with "activeFlag:1". My query object code is

findAccountObj = 
{ _id: objectID(req.body.accountId),
 ownerId: req.body.userId,
 bookId: req.body.bookId,
"notes.activeFlag": 1 };

But this query returns all the notes, including the ones with "activeFlag:0". How do I fix this?


Solution

  • If you are on v2.2, use elementmatch operator. v3.2 and above allow aggregation and filter to return a subset of a document.

    here is an example Retrieve only the queried element in an object array in MongoDB collection