简体   繁体   中英

Get index of an element mongodb aggregation

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..

You can $unwind with includeArrayIndex to get the index of address array

db.t11.aggregate([
    {$match : {"adress.street" : "ben street"}},
    {$unwind : {path : "$adress", includeArrayIndex : "idx"}},
    {$match : {"adress.street" : "ben street"}}
]).pretty()

you can add $project to filter the fields not required

result

> db.t11.aggregate([{$match : {"adress.street" : "ben street"}},{$unwind : {path : "$adress", includeArrayIndex : "idx"}},{$match : {"adress.street" : "ben street"}}]).pretty()
{
        "_id" : ObjectId("5c225f9a66d39d55c036fa66"),
        "name" : "Sherlock",
        "mobile" : "999999",
        "adress" : {
                "street" : "ben street",
                "city" : "london"
        },
        "tags" : [
                "Detective",
                "Magician",
                "Avenger"
        ],
        "idx" : NumberLong(1)
}
>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM