【问题标题】:Finding a nested object in an array of object using mongoose使用猫鼬在对象数组中查找嵌套对象
【发布时间】:2022-01-14 17:13:59
【问题描述】:
{
  _id: new ObjectId("61da0ab855483312e8f4483b"),
  products: [
    {
      createdAt: 2022-01-08T22:05:44.635Z,
      _id: new ObjectId("61da0ab855483312e8f4483c"),
      productCode: 'otf',
      productName: 'facebookmeta',
      claims: [Array],
      permissions: []
    },
    {
      createdAt: 2022-01-08T22:05:44.635Z,
      _id: new ObjectId("61da0ab855483312e8f4483f"),
      productCode: '4pf',
      productName: 'twitteroauth',
      claims: [Array],
      permissions: [Array]
    }
  ],
  __v: 0
}

现在我一直在尝试使用 find() 和 findOne 方法从这个数组中获取一个对象,但没有任何运气。如果我在某些条件下通过,它最终仍然会给我一个包含两个对象的数组。我只是希望能够动态传递属于数组中单个对象的条件并检索该对象

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

MongoDB 正在对集合应用查询条件,并返回匹配文档的结果。由于 twitteroauthfacebookmeta 两个产品都是同一个文档的一部分,因此将返回整个匹配的文档。

如果您只想要文档中的单个匹配条目,那么您可以使用 MongoDB 聚合管道(使用 $unwind),您可以在其中修改结果集。

例如:

db.collection_name.aggregate([
   {
     "$match": {
        // pass matching criteria/conditions here
     }
   },
   {
      "$unwind": "$products" //to deconstruct products field in the result
   },
   {
     "$match": {
        "products.productName": "twitteroauth"
     }
   }
])

请注意,第二个匹配条件用于在解构的结果集上添加额外的匹配条件/条件,以便过滤产品。

这将为您提供如下结果:-

{
  _id: new ObjectId("61da0ab855483312e8f4483b"),
  products: {
    createdAt: 2022-01-08T22:05:44.635Z,
    _id: new ObjectId("61da0ab855483312e8f4483f"),
    productCode: '4pf',
    productName: 'twitteroauth',
    claims: [Array],
    permissions: [Array]
  },
  __v: 0
}

参考:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

【讨论】:

  • 谢谢陌生人!!!
猜你喜欢
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 2019-10-12
  • 2016-02-05
  • 2020-02-20
相关资源
最近更新 更多