Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of an element mongodb aggregation

Tags:

Here is my collection

{
        "_id" : ObjectId("5c225f9a66d39d55c036fa66"),
        "name" : "Sherlock",
        "mobile" : "999999",
        "adress" : [
                {
                        "street" : "221b baker street",
                        "city" : "london"
                },
                {
                        "street" : "ben street",
                        "city" : "london"
                }
        ],
        "tags" : [
                "Detective",
                "Magician",
                "Avenger"
        ]
}

Now I want to get the first or second value inside address array. for that I'm using this command.

> db.agents.findOne({"name" : "Sherlock"},{"adress" : 1})

but instead of giving a single result it is giving the entire array like

{
        "_id" : ObjectId("5c225f9a66d39d55c036fa66"),
        "adress" : [
                {
                        "street" : "221b baker street",
                        "city" : "london"
                },
                {
                        "street" : "ben street",
                        "city" : "london"
                }
        ]
}

It can be done by comparing array value like

 db.agents.find({"adress.street": "ben street"}, {_id: 0, 'adress.$': 1});

But I don't want to compare just to print the array indexes. How can I get the single result? Any help is appreciated..

like image 633
shubham kakade Avatar asked Dec 29 '18 03:12

shubham kakade


1 Answers

You can use $arrayElemAt to get the specific element from the array

db.collection.aggregate([
  { $addFields: { "$arrayElemAt": ["$adress", 0] }}   //index
])

and if you want to get the sliced element then you can use $slice projection

db.collection.find({}, { adress: { $slice: [2, 1] }})  // 2 index and 1 number of element
like image 148
Ashh Avatar answered Nov 15 '22 07:11

Ashh