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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With