简体   繁体   中英

Mongoose: Filter nested documents

I have a MongoDB collection with documents that follows this shape:

"peopleList": [
 {
  "_id": "List 1 id",
  "name": "List 1",
  "people": [
    {
      "_id": "A Person id",
      "name": "A Person",
      "email": "person@email.com"
    },
    {  
      "_id": "Another Person id",
      "name": "Another Person",
      "email": "another.person@email.com"
    },
  ],
 },
 {
  "_id": "List 2 id",
  "name": "List 2",
  "people": [
    {
      "_id": "A Person id",
      "name": "A Person",
      "email": "person@email.com"
    },
  ],
 }
]

As you can see, the same Person object can appear in multiple lists.

So what I want is to retrieve all lists that a given person is part.

For eg:

Passing _id: "A Person id" -> the query should return List 1 and List 2,

Passing _id: "Another Person id:" -> the query should return only List 1.

I tried this query:

await PeopleList.find({ people: { _id: 'A person id' } });

But the query returned an empty array, even 'A person id' is a document present in many lists.

EDIT

Sharing the Fahad answer, the correct query is:

await PeopleList.find({
  people: { $elemMatch: { _id: mongoose.Types.ObjectId('A person id') } 
}});

Lets assume that your mongo schema name is PeopleList so your filter query will be like this

PeopleList.find({people : {$elemMatch:{_id: mongoose.Types.ObjectId('321321321321321')}});

For more info you can see documentation here

You have to use $elemMatch and $in to find in array. So try like this

 "people": { $elemMatch: { "_id": { $in: [mongoose.Types.ObjectId(params.id) ] } } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM