我是 MongoDB 的新手...我缺少“新手”标签,因此专家不必看到这个问题。
我正在尝试使用表达式更新集合中的所有文档。我期望解决这个问题的查询是:
db.QUESTIONS.update({}, { $set: { i_pp : i_up * 100 - i_down * 20 } }, false, true);
但是,这会导致以下错误消息:
ReferenceError: i_up is not defined (shell):1
同时,数据库吃这个也没问题:
db.QUESTIONS.update({}, { $set: { i_pp : 0 } }, false, true);
我是否必须一次处理一份文件或其他什么?这看起来太复杂了。
更新 谢谢 Sergio Tulentsev 告诉我它不起作用。现在,我真的在为如何做到这一点而苦苦挣扎。我提供 500 Profit Points献给乐于助人的人,他们可以用 MongoDB 理解的方式写这篇文章。如果您在 our forum 上注册我可以在那里将利润点添加到您的帐户。
最佳答案
我只是在搜索与 SQL 等效的 MongoDB 时遇到了这个问题:
update t
set c1 = c2
where ...
Sergio 是正确的,您不能在直接更新中引用另一个属性作为值。但是,db.c.find(...)
返回 cursor and that cursor has a forEach
method :
Queries to MongoDB return a cursor, which can be iterated to retrieve results. The exact way to query will vary with language driver. Details below focus on queries from the MongoDB shell (i.e. the
mongo
process).The shell
find()
method returns a cursor object which we can then iterate to retrieve specific documents from the result. We usehasNext()
andnext()
methods for this purpose.for( var c = db.parts.find(); c.hasNext(); ) { print( c.next()); }
Additionally in the shell,
forEach()
may be used with a cursor:db.users.find().forEach( function(u) { print("user: " + u.name); } );
所以你可以这样说:
db.QUESTIONS.find({}, {_id: true, i_up: true, i_down: true}).forEach(function(q) {
db.QUESTIONS.update(
{ _id: q._id },
{ $set: { i_pp: q.i_up * 100 - q.i_down * 20 } }
);
});
在不离开 MongoDB 的情况下一次更新它们。
如果您使用驱动程序连接到 MongoDB,那么应该有某种方法可以将 JavaScript 字符串发送到 MongoDB;例如,对于 Ruby 驱动程序,您将使用 eval
:
connection.eval(%q{
db.QUESTIONS.find({}, {_id: true, i_up: true, i_down: true}).forEach(function(q) {
db.QUESTIONS.update(
{ _id: q._id },
{ $set: { i_pp: q.i_up * 100 - q.i_down * 20 } }
);
});
})
其他语言应该类似。
关于mongodb - 用表达式而不是值更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10180687/