Reputation: 467
{
"_id" : 123,
"someKey" : "someValue",
"someArray" : [
{
"name" : "name1",
"someNestedArray" : [
{
"name" : "value_1",
"fame" : [
{
"goal" : "goal_1"
}
]
},
{
"name" : "value_2",
"fame" : [
{
"goal" : "goal_2"
}
]
}
]
}
]
}
I does the query like:
db.getCollection('city').find({"someArray.0.someNestedArray.1.fame.0.goal":"goal_2"},{"someArray.0.someNestedArray.":1})
But get the output as:
{
"_id" : 123,
"someArray" : [
{}
]
}
What is the query for getting the output as:
{
"fame" : [
{
"goal" : "goal_2"
}
]
}
Thanks in advance. Also tell how to find a value in nested array when one don't know the indexes. The query I have done specifies the array element position (someArray.0.someNestedArray.1.fame.0.goal)
Upvotes: 2
Views: 952
Reputation: 11477
You can just use this following query:
db.test.find(
{'someArray.someNestedArray.fame.goal':'goal_1'},
{"someArray.someNestedArray.fame.goal":1,"_id":0}
)
And you will get the document:
{
"someArray" : [
{
"someNestedArray" : [
{
"fame" : [
{
"goal" : "goal_1"
}
]
},
{
"fame" : [
{
"goal" : "goal_2"
}
]
}
]
}
]
}
Also you can try to use $elemMatch
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
db.test.find(
{
'someArray':{
$elemMatch:{
'someNestedArray':{
$elemMatch:{
'fame':{ $elemMatch: {"goal" : "goal_2" } }
}
}
}
}
},{"someArray.someNestedArray.fame.goal":1}
);
You can try to use $unwind and $replaceroot to return subdocument,and use the new $filter aggregation operator to filter an array during projection.
Hope this helps.
Upvotes: 3