Reputation: 17322
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
).
Upvotes: 0
Views: 8255
Reputation: 37018
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}
)
Upvotes: 2
Reputation: 48346
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});
Upvotes: 0