简体   繁体   English

使用 mongoose 在 object 数组中查找嵌套的 object

[英]Finding a nested object in an array of object using mongoose

{
  _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
}

Now i've been trying to get just one object from this array with the find() and findOne method without any luck.现在,我一直在尝试使用 find() 和 findOne 方法从该数组中仅获取一个 object ,但没有任何运气。 if i pass in a certain conditions, it still ends up giving me back an array with both objects.如果我在某些条件下通过,它仍然会最终给我一个包含两个对象的数组。 i just want to be able to dynamically pass conditions that belongs to a single object in the array and retrieve that object我只想能够动态传递属于数组中单个 object 的条件并检索该 object

MongoDB is applying query conditions on collection and returns the result with the matching documents. MongoDB 正在对集合应用查询条件并返回结果与匹配的文档。 As both products twitteroauth & facebookmeta are part of the same document so the whole matching document will be returned.由于twitteroauthfacebookmeta两个产品都是同一文档的一部分,因此将返回整个匹配文档。

If you want only a single matching entry in the document then you can use the MongoDB aggregation pipeline (with $unwind) where you can modify the result set.如果您只需要文档中的单个匹配条目,则可以使用 MongoDB 聚合管道(带有 $unwind),您可以在其中修改结果集。

For example:例如:

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

Note that the second match condition is used to add additional matching criteria/conditions on the deconstructed result set so that products can be filtered.请注意,第二个匹配条件用于在解构的结果集上添加其他匹配条件/条件,以便可以过滤产品。

This will get you the result something like this:-这将为您提供如下结果:-

{
  _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
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM