简体   繁体   English

MongoDB where子句更新

[英]MongoDB where clause update

I have a collection named 'profiles_bak' .i'd like to update the every document in the 'profiles_bak'.for a single condition the below mention code is working fine 我有一个名为'profiles_bak'的集合。我想更新'profiles_bak'中的每个文档。对于单个情况,下面提到的代码可以正常工作

 db.profiles_bak.update(
  {$where : "this.value1 > this.value2"},
  {$set : {"Gender": "male" }},false,true)

but i have to update based on multiple condition also i have mention my code what i have used so far or else any other approach how i can achieved this. 但是我必须基于多个条件进行更新,我也提到了我到目前为止使用的代码,或者其他任何可以实现此目标的方法。

db.profiles_bak.update( { $and: [
    {query: { $where : "this.value1 > this.value2" },
    update: { $set : {"Gender": "male" }},false,true},
 {query: { $where : "this.value1 < this.value2" },
    update: { $set : {"Gender": "female" }},false,true}
 ]})

You cannot do that. 你不能这样做。 Whilst you can construct an expression with JavaScript evaluation it cannot "alter" the the chosen result in the "update" block of the statement. 尽管可以使用JavaScript评估构造表达式,但是它不能在语句的“更新”块中“更改”所选结果。 Query logic is separated from the update statement block, and that statement block can only do exactly a singular operation based on the query conditions met. 查询逻辑与update语句块分开,并且该语句块只能根据满足的查询条件精确地执行单个操作。

These are "two" update statements. 这是“两个”更新语句。 Use the Bulk Operations API to make it more efficient: 使用Bulk Operations API提高效率:

var bulk = db.profiles_bak.initializeUnorderedBulkOp();

bulk.find({ "$where": "this.value1 > this.value2" }).update({
    "$set": { "Gender": "male" }
});
bulk.find({ "$where": "this.value1 < this.value2" }).update({
    "$set": { "Gender": "female" }
});
bulk.execute();

At least that is one request to the server an one reponse. 至少那是对服务器的一个请求。

The .update() in Bulk is always set to "multi". 批量中的.update()始终设置为“多”。

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

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