【问题标题】:Mongoose: Filter nested documentsMongoose:过滤嵌套文档
【发布时间】: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


    【解决方案1】:

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

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

    有关更多信息,您可以查看文档here

    【讨论】:

    • 它不起作用。通过插入 {people._id: "A person id"} ,应用程序由于解析错误而崩溃。
    • SyntaxError: Unexpected token, expected ","
    • 我做的精确查询是:lists = await PeopleList.find({ people._id : authorId }).select([ '-__v', '-updatedAt', '-createdAt' ]) ;
    • 在 .find() 之后暂时删除 .select 和所有这些,然后尝试更新查询。
    • 在您的authorId 中,您能说出authorId 中的内容吗?并且请在您的问题帖子中添加您尝试过的查询代码,以便我可以确保您是否尝试了正确的事情
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢甘地!有效。我标记了 Fahad 的答案,因为他首先回答。不过非常感谢。
    猜你喜欢
    • 2019-08-09
    • 2016-04-25
    • 2019-07-19
    • 2019-07-13
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2012-01-15
    • 2017-05-03
    相关资源
    最近更新 更多