繁体   English   中英

Mongod DB使用条件更新数组元素顺序

[英]Mongod DB update array element order with condition

我想用条件对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运算符执行upsert操作,该运算符会根据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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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