Aggregate - return the whole array if query match one element in the array

535 views
Skip to first unread message

Flavio Oliveira

unread,
Jun 2, 2016, 6:13:46 AM6/2/16
to mongodb-user
Hi,

Given the document below:

{
    "chainId" : 317,
    "chain" : [ 
        {
            "name" : "ONE",
            "tierLevel" : 1
        }, 
        {
            "name" : "TWO",
            "tierLevel" : 2
        }, 
        {
            "name" : "THREE",
            "tierLevel" : 3
        }
    ]
}

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' ] }}}}}])

Regards, Flavio

Rhys Campbell

unread,
Jun 2, 2016, 1:14:05 PM6/2/16
to mongodb-user
I'm not 100% sure if the aggregation framework support it but you can do this woith a standard find...

db.rhys.find( { "chain.2.name": "THREE" }, { "chain": { "$slice": 1 } } ).pretty();


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.



Kevin Adistambha

unread,
Jun 20, 2016, 2:01:09 AM6/20/16
to mongodb-user

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


Reply all
Reply to author
Forward
0 new messages