简体   繁体   中英

mongoDB: get field value of an array object

I want to get the value of the field 30 in the object (in the array test ) with the id ePce6fBAHx9KeKjuM .

{
    "_id" : "nAwt3b76c24mZfqxz",
    "title" : "test",
    "test" : [
        {
            "4" : false,
            "15" : false,
            "30" : false,
            "75" : true,
            "id" : "ePce6fBAHx9KeKjuM"
        }
    ]
}

So this result would be false

I tried something like

var result = Collection.findOne({_id: 'nAwt3b76c24mZfqxz'}).test;

But this would give me the complete array. But I need the selected object and only a selected field of this object (ie. 30 ).

test is just a JS array. Use normal array syntax to access its elements:

var result = Collection.findOne({_id: 'nAwt3b76c24mZfqxz'}).test["30"];

EDIT:

To retrieve the whole object with only 1 element of the array use projection, as of zangw's answer. Following your comment to test element itself:

db.getCollection('a').find(
    // put your nested document's condition instead of `$exists`
    {_id: 'nAwt3b76c24mZfqxz', test:{ $elemMatch: { "30": {$exists: true}}}},
    // add other fields you like to retrieve, e.g. "title":1
    {"test.30":1}
)

Try this one

Collection.find({{_id: 'nAwt3b76c24mZfqxz'}}, {'test.30': 1, 'test.id': 1});

To select the whole test array as following without _id

Collection.find({{_id: 'nAwt3b76c24mZfqxz'}}, {'test': 1, '_id': 0});

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