Remove nested document with condition in MongoDB

感情迁移 提交于 2019-12-11 19:16:18

问题


For the following JSON how do I remove the dog whose height is the least

{
   _id:0
   "name":"Andy",
   "pets":[
      {
         "type":"dog","name":"max","height":120
      },
      {
         "type":"dog","name":"rover","height":44
      },
      {
         "type":"dog","name":"katie","height":100
      },
      {
         "type":"cat","name":"minni"
      }
   ]
}

回答1:


The problem is the array of subdocuments is not a collection, you can't sort or do something else on it. But if you have an access to any language interface like JavaScript or else it's possible. You just need to extract list of subdocuments, sort them by height, remember the first one and then run the command to pull it from the array based on its name and height. It can be done for example using this JavaScript code right in the MongoDB shell:

var min = 0; var name = "";
db.animals.find({ query:{"_id" : 0} }).forEach(
function(record){
    var sets = record.pets; 
    min = sets[0].height;
    sets.forEach(function(set){
        if(set.height <= min) 
            {min=set.height;
            name=set.name;}
            });
    print(min);
    print(name);    
    query = {"_id": 0}
    update = { "$pull" : { "pets" : { "name" : name } } };
    db.animals.update(query, update);
    })

I suspect the solution is not the most elegant but anyway it works.



来源:https://stackoverflow.com/questions/13388791/remove-nested-document-with-condition-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!