【发布时间】:2020-05-02 21:05:51
【问题描述】:
我有一个 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"
},
],
}
]
如您所见,同一个 Person 对象可以出现在多个列表中。
所以我想要的是检索给定人员所属的所有列表。
例如:
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' } });
但是查询返回了一个空数组,即使“A person id”是一个存在于许多列表中的文档。
编辑
分享法赫德的答案,正确的查询是:
await PeopleList.find({
people: { $elemMatch: { _id: mongoose.Types.ObjectId('A person id') }
}});
【问题讨论】:
标签: javascript node.js mongodb mongoose