{
_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 方法從這個陣列中獲取一個物件,但沒有任何運氣。如果我在某些條件下通過,它仍然會最終給我一個包含兩個物件的陣列。我只想能夠動態傳遞屬于陣列中單個物件的條件并檢索該物件
uj5u.com熱心網友回復:
MongoDB 對集合應用查詢條件,并回傳匹配檔案的結果。由于twitteroauth和facebookmeta兩個產品都是同一檔案的一部分,因此將回傳整個匹配檔案。
如果您只想要檔案中的單個匹配條目,那么您可以使用 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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411676.html
標籤:
下一篇:MongoDB查詢優化
