簡體   English   中英

返回Mongodb子文檔中的一組數據

[英]Return one array of data in sub-document of Mongodb

我正在使用帶有 ZCCADCDEDB567ABAE643E15DCF0974E503Z package 的 Nodejs。 鑒於我有這樣的事情: -

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

我只想使用它的_id獲取pets arrayJerry的數據(結果如下所示)

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

假設嵌套數組的_id是唯一的,您可以直接按嵌套數組元素過濾:

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

暫無
暫無

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

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