Reputation: 1209
Let us say I have the following JSON Object
[
{
"id":"1",
"fruitName":{
"name":"Apple",
"color":"Red"
}
},
{
"id":"2",
"fruitName":{
"name":"Mango",
"color":"Yellow"
}
},
{
"id":"3",
"vegetableName":{
"name":"Cabbage",
"color":"Green"
}
}
]
I want to sort them by name alphabetically which are located inside two different fields (fruitName and vegetableName).
Is there any way to do it in Spring Mongo without modifying the JSON Object so the output would be like this.
[
{
"id":"1",
"fruitName":{
"name":"Apple",
"color":"Red"
}
},
{
"id":"3",
"vegetableName":{
"name":"Cabbage",
"color":"Green"
}
},
{
"id":"2",
"fruitName":{
"name":"Mango",
"color":"Yellow"
}
}
]
Upvotes: 0
Views: 206
Reputation: 1382
Yes you can do it without modifying the JSON Object by using Projection with condition.
db.collection.aggregate([{
$project: {
id: 1,
fruitName: 1,
vegetableName: 1,
name: { $ifNull: ['$fruitName.name', '$vegetableName.name'] },
}
}, {
$sort: {
name: 1
}
}])
If you are using mongodb version 3.4+, then you can use addFields also.
db.collection.aggregate([{
$addFields: {
name: { $ifNull: ['$fruitName.name', '$vegetableName.name'] }
}
}, {
$sort: {
name: 1
}
}])
Upvotes: 1