簡體   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
}

現在,我一直在嘗試使用 find() 和 findOne 方法從該數組中僅獲取一個 object ,但沒有任何運氣。 如果我在某些條件下通過,它仍然會最終給我一個包含兩個對象的數組。 我只想能夠動態傳遞屬於數組中單個 object 的條件並檢索該 object

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM