0

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).

2 Answers 2

2

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}
)
Sign up to request clarification or add additional context in comments.

2 Comments

But this doesn't consider, that test is an array, and I need the result of the object with the given id.
It would be nice to have an example of expected result, as it is not quite clear what you are trying to retrieve.
0

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});

3 Comments

But I need the exact object of the array test (id = ePce6fBAHx9KeKjuM).
@user3142695, add {test : 1} to select this field out.. Is it meet your requirement? or am I missing something?
I'm not quite sure, but this just selects the field generally. I have to check the defined object in this array. So if there isn't an object with the given id, the result should be empty/false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.