Let's say I have these documents
> db.coll.find().toArray()
[
{
"_id" : ObjectId("5a36c3e218948d0722457078"),
"locality" : "Nasimi, Baku, Azerbaijan"
},
{
"_id" : ObjectId("5a36c3e218948d0722457079"),
"locality" : "Garland, TX, USA"
},
{
"_id" : ObjectId("5a36c3e218948d072245707a"),
"locality" : "Halytskyi District, Lviv, Lviv Oblast, Ukraine"
},
{
"_id" : ObjectId("5a36c3e218948d072245707b"),
"locality" : "Tozeur, Tunisia"
}
]
I would like to get only the country, ie whatever is after the last comma ( ', '
).
eg
[
"Azerbaijan",
"USA",
"Ukraine",
"Tunisia"
]
I've managed to get the index of the first comma and what is after that but I can't figure out how to to get the last one.
db.coll
.aggregate([
{
$project: {
lastIndexOf: { $indexOfBytes: [ '$locality', ', ' ] },
locality: '$locality',
}
},
{
$project: {
lastIndexOfPlusTwo: { $add: [ '$lastIndexOf', 2 ] },
locality: '$locality',
}
},
{
$project: { country: { $substr: [ '$locality', '$lastIndexOfPlusTwo', -1 ] } }
}
]).pretty()
{
"_id" : ObjectId("5a36c3e218948d0722457078"),
"country" : "Baku, Azerbaijan"
}
{
"_id" : ObjectId("5a36c3e218948d0722457079"),
"country" : "TX, USA"
}
{
"_id" : ObjectId("5a36c3e218948d072245707a"),
"country" : "Lviv, Lviv Oblast, Ukraine"
}
{
"_id" : ObjectId("5a36c3e218948d072245707b"),
"country" : "Tunisia"
}
This works but it loads all the results in memory in the JavaScript Mongo Shell but would be ideal if it can be done with a single MongoDB aggregation command.
var res2 = db.coll.aggregate();
res2 = res2.toArray().map(function(doc) {
var lastIndex = doc.locality.lastIndexOf(',');
return doc.locality.slice(lastIndex + 2);
});
[ "Azerbaijan", "USA", "Ukraine", "Tunisia" ]
You can try below aggregation query.
{"$arrayElemAt":["$$locality",-1]}
to access the last element from the array.
db.coll.aggregate([{"$project":{
"_id":0,
"last":{
"$let":{
"vars":{"locality":{"$split":["$locality",","]}},
"in":{"$arrayElemAt":["$$locality",-1]}
}
}
}}])
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.