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

2019-02-19 17:31发布

问题:

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 <> 0

The a = b part is what I can't figure out. I tried mongodb.org, but I can't find it there. I also looked for WHERE a = b but I can't find that either.

An alternative is so fetch all rows and than update them individually, but I don't like that. It has to be simpler.

Thanks.

回答1:

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();


标签: mongodb nosql