How to “(WHERE) column = column” in Mongo?

前端 未结 1 973
难免孤独
难免孤独 2021-01-15 05:36

I like Mongo for simple things so I was hoping to use it for something more advanced. And that worked fine until I needed this:

UPDATE tbl SET a = b WHERE c          


        
相关标签:
1条回答
  • 2021-01-15 06:28

    You want to check the documentation for updating.
    http://www.mongodb.org/display/DOCS/Updating

    Your code might look like:
    db.tbl.update( { c:{$ne:0}}, { $set: { a : b } } );

    If you need to brush up on advanced queries (e.g. using $ne), then check here:
    http://www.mongodb.org/display/DOCS/Advanced+Queries

    EDIT:
    Apparently you can't update with data from the same document.
    MongoDB: Updating documents using data from the same document

    EDIT 2 (solution with map reduce):

    var c = new Mongo();
    var db = c.getDB('db')
    var s = db.getCollection('s')
    s.drop();
    s.save({z:1,q:5});
    s.save({z:11,q:55});
    
    db.runCommand({
    mapreduce:'s',
    map:function(){
      var i = this._id; //we will emit with a unique key. _id in this case
      this._id=undefined; //strange things happen with merge if you leave the id in
      //update your document with access to all fields!
      this.z=this.q;
    
      emit(i,this);
    }, 
    query:{z:1},    //apply to only certain documents
    out:{merge:'s'} //results get merged (overwrite themselves in collection)
    });
    
    //now take a look
    s.find();
    
    0 讨论(0)
提交回复
热议问题