Would return...
{
"_id" : ObjectId("575065636b36b470e72d53c9"),
"chainId" : 317,
"chain" : [
{
"name" : "ONE",
"tierLevel" : 1
}
]
}Additionally I'm not sure the $projection phase would use indexes. Might be better to use $match in the pipeline first.
Hi Flavio,
How do I get the first element of this array based on a query on the third element? If the name in the third object is THREE, I also want the first Object.
I tried $filter, but it only returns an array with the elements that match the condition.db.sp.aggregate([{$project: {test: {$filter: {input: "$chain",as: "item",cond: { $eq: [ "$$item.name", 'THREE' ] }}}}}])
I’m a bit unclear about your goal. The title of your post mentions “return the whole array”, but in the body of your post you mention you want the first object.
Assuming you want your query to return the whole array, you can use the find() method as Rhys has suggested:
db.sp.find({'chain.2.name':'THREE'})
or using the $match stage of aggregation, which will result in the same output:
db.sp.aggregate([{$match:{'chain.2.name':'THREE'}}])
If you need to return only the first element of the array, then Rhys’ query will do the trick.
However, if this is not what you require, could you please post more examples of input and output documents, and also your MongoDB version?
On a side note, the $project stage of aggregation pipeline cannot use indexes.
Best regards,
Kevin