【问题标题】:Return one array of data in sub-document of Mongodb返回MongoDB子文档中的一组数据
【发布时间】:2020-09-22 21:31:04
【问题描述】:

我正在使用带有 Mongoose 包的 Nodejs。 鉴于我有这样的事情:-

let people = [
    {
        "_id": 1,
        "name": "Person 1",
        "pets": [
            {
                "_id": 1,
                "name": "Tom",
                "category": "cat" 
            },
            {
                "_id": 2,
                "name": "Jerry",
                "category": "mouse" 
            }
        ]
    }
]

我只想使用pets array 中的Jerry 获取_id 的数据(结果如下图)

{
     "_id": 2,
     "name": "Jerry",
     "category": "mouse" 
}

在使用$elemMatch时,我可以不用指定person 1_id就可以得到它吗?现在我的代码是这样的:-

const pet = People.find(
    { "_id": "1"}, // specifying 'person 1 _id' first
    { pets: { $elemMatch: { _id: 2 } } } // using 'elemMatch' to get 'pet' with '_id' of '2' 
)

它给了我想要的东西,就像我在上面向你展示的那样。但是还有其他方法我可以做到这一点不需要先指定它的父级的_id(在这种情况下,people array_id )

【问题讨论】:

  • 您可以使用positional $ projection operator。但是,您仍然需要指定数组字段被限制 - 必须 出现在查询过滤器中。这与使用 $elemMatch 相同 - 只是 $elemMatch 投影在使用多个字段进行投影时很有用。
  • 您在filter 中指定{ "_id": "1"} 只是为了确保在响应和投影中只获得一个文档,您使用$elemMatch 匹配pets 数组中的相应对象,因此,如果您从过滤器中删除 { "_id": "1"},那么您将在 o/p 中获得多个文档(所有文档在 pets 数组中至少有一个带有 "_id": 2 的对象)

标签: arrays mongodb mongoose nested mongodb-query


【解决方案1】:

假设嵌套数组的 _id 是唯一的,您可以直接按嵌套数组元素进行过滤:

const pet = People.find(
    { "pets._id": 2 },
    { pets: { $elemMatch: { _id: 2 } } }
)

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2023-04-05
    • 2021-12-03
    • 2013-10-04
    • 2019-07-09
    • 2014-05-28
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多