简体   繁体   中英

Return one array of data in sub-document of Mongodb

I'm using Nodejs with Mongoose package. Given I've something like this:-

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

I want to get only the data of Jerry in pets array using it's _id (result shown below)

{
     "_id": 2,
     "name": "Jerry",
     "category": "mouse" 
}

Can I get it without needing to specify the _id of person 1 when using $elemMatch ? Right now I code like this:-

const pet = People.find(
    { "_id": "1"}, // specifying 'person 1 _id' first
    { pets: { $elemMatch: { _id: 2 } } } // using 'elemMatch' to get 'pet' with '_id' of '2' 
)

And it gave me what I want like I've shown you above. But is there any other way I can do this without needing to specify the _id of it's parent first (in this case, the _id of the people array )

Assuming nested array's _id 's are unique you can filter by nested array elements directly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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