我想用条件对Mongodb数组元素进行排序
假设我的数组是这样的
{
"id":1,
"array":[
{
"id" : "150",
"place" : "US"
},
{
"id" : "1250",
"place" : "UK"
},
{
"id" : "1350",
"place" : "AUS"
}
]
}
然后我想排序和更新"数组"例如:我想按 1250、1350、150 的顺序排列数组元素值"id"
更新的文档将如下所示
{
"id":1,
"array":[
{
"id" : "1250",
"place" : "UK"
},
{
"id" : "1350",
"place" : "AUS"
},
{
"id" : "150",
"place" : "US"
},
]
}
将 $push 运算符与 $each 和 $sort 修饰符一起使用。
db.collection.update({"id":1},
{$push:{"array":{$each:[],$sort:{"id":1}}}})
将空数组传递给 $each
修饰符可确保不添加其他元素,并且仅根据id
字段按词法升序排序现有元素(因为id
是字符串类型)。
若要使用
$sort
修饰符,它必须与$each
修饰符一起显示。你 可以将空array []
传递给$each
修饰符,以便只有$sort
修饰符都有效果。
如果您想根据 id 字段上的某些优先级对其进行排序,那么您可以在应用程序代码中执行此操作,如下所示:
// define an array of elements with decreasing priority
var sortOrder = ["1250","1350","150"];
// find and update all the documents
db.collection.find().forEach(function(doc){
var arr = doc.array.sort(function(a,b){
return (sortOrder.indexOf(a.id) - sortOrder.indexOf(b.id));
})
db.collection.update({"_id":doc._id},{$set:{"array":arr}});
})
但我建议的最佳方法是在插入文档或更新array
字段时保持顺序。
具有id
字段的映射,以确定元素在数组字段中需要排序的顺序。
var sortOrder = ["1350","1250","150"];
每当要insert/update
时,请使用 $position 运算符执行更新插入操作,该运算符根据数组sortOrder
数组将新元素inserts/updates
数组字段。
var elementToInsert = {"id":"1350","place":"UK"};
db.collection.update({"id":1},
{$push:{"array":{$each:
[elementToInsert],
$position:sortOrder.indexOf(elementToInsert.id)}}},
{"upsert":true})
db.collection.find().sort( { id: 1 } ).pretty();