猫鼬:过滤嵌套文档

时间:2020-01-16 03:19:44

标签: javascript node.js mongodb mongoose

我有一个MongoDB集合,其中的文档遵循以下形状:

"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"
    },
  ],
 }
]

如您所见,同一个人对象可以出现在多个列表中。

所以我要检索的是给定人员参与的所有列表。

例如:

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.

我尝试了以下查询:

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

但是查询返回了一个空数组,即使'Person ID'是存在于许多列表中的文档。

编辑

共享Fahad答案,正确的查询是:

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

2 个答案:

答案 0 :(得分:0)

让我们假设您的mongo schema名称为PeopleList,因此您的过滤器查询将是这样

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

有关更多信息,请参阅文档here

答案 1 :(得分:0)

您必须使用$elemMatch$in在数组中查找。所以像这样

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