简体   繁体   English

Meteor / Mongo:查找和更新集合中的某些元素

[英]Meteor/Mongo: Finding and updating certain elements in a collection

I'm starting off with Meteor and need some help with Mongo. 我从Meteor开始,需要一些Mongo的帮助。 I have a collection of names that I'm displaying on a list and want to be able to update one variable of certain entries in the database based on other criteria. 我有一组名称,我正在列表中显示,并希望能够根据其他条件更新数据库中某些条目的一个变量。 Basically what I want to do is: 基本上我想做的是:

For every entry where characteristic A = true and B = true, change characteristic C to be false. 对于特征A =真且B =真的每个条目,将特征C改变为假。

So far, I've been trying to figure out how Mongo can handle a "for each" loop over the elements of the collection, and for each element check if conditions A and B hold, and then collection.update(element, {C: false}). 到目前为止,我一直在试图弄清楚Mongo如何处理集合元素的“for each”循环,并且每个元素检查条件A和B是否成立,然后是collection.update(element,{C :false})。 This is proving to be a lot more problematic than I thought. 事实证明这比我想象的要多得多。 I want to do something like this (using dummy variable names): 我想做这样的事情(使用虚拟变量名称):

for (i = 0; i < collection.find().count(); i++){
    if (collection[i].A===true && collection[i].B===true)
        collection.update(collection[i], {$set: {C: false}});
};

I've been changing this base code around, but am starting to sense that I'm missing something basic about indexing/how collections work in Mongo. 我一直在改变这个基本代码,但我开始意识到我缺少一些关于索引/ Mongo如何在集合中工作的基本知识。 Can you index a collection like this (and if so, is this even the most convenient way to do what I'm trying to do?)? 你可以像这样索引一个集合(如果是这样,这甚至是我做我想做的最方便的方式吗?)?

Of course I figure out how to do this right after posting, and of course it's suggested in the Meteor documentation! 当然,我想知道如何在发布后立即执行此操作,当然,这是在Meteor文档中建议的!

And, of course, it's a simple solution: 当然,这是一个简单的解决方案:

collection.update({A: true, B: true}, {$set: {C:false}});

As already suggested in comments, the correct answer is: 正如评论中已经建议的那样,正确的答案是:

collection.update({A: true, B: true}, {$set: {C:false}}, {multi: true});

(At least in pure MongoDB, see there ). (至少在纯MongoDB中, 请参见 )。

Without multi: true it will change only one document matching the criteria. 如果没有multi: true ,它将只更改一个符合条件的文档。

In Meteor it is a bit more tricky, as you are not allowed to do client-side updates other than by matching it (so no possibility for various criteria, no possibility for multi ), see http://docs.meteor.com/#update . 在Meteor中它有点棘手,因为除了匹配它之外你不允许进行客户端更新(因此不可能有各种标准,不可能有multi ),请参阅http://docs.meteor.com/ #update

You can iterate over all finds, but it would be better to run such code server-side. 可以迭代所有查找,但最好运行此类代码服务器端。

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

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