我知道我可以做这样的事情来更新字段到一个特定的值。
db.coll.update({},{ $set: {'fieldName': 'fieldValue' } }, { multi:true });
然而,我需要更新一个字段的值,等于同一文档中一个数组字段的值的数量。 我知道这可能需要聚合函数,但我对Mongo比较陌生,需要一些帮助来构造查询。 它还需要对集合中的每个文档进行查询。
让我们假设我们的集合看起来像下面。
{
"_id" : 1
"array" : [
1,
2,
3
]
},
{ "_id" : 2,
"array" : [
1
]
},
{
"_id" : 3
"array" : [
1,
2,
3,
4,
5,
6
]
}
所需的查询是:
db.collection.update({},[{$set: {size: {$size: '$array'}}}], {multi: true})
下面将是更新后的集合。
{
"_id" : 1,
"array" : [
1,
2,
3
],
"size" : 3
}
{
"_id" : 2,
"array" : [
1
],
"size" : 1
}
{
"_id" : 3,
"array" : [
1,
2,
3,
4,
5,
6
],
"size" : 6
}
这个查询最终为我工作:
var bulkOp = db.posts.initializeUnorderedBulkOp();
var count = 0;
db.posts.aggregate([
{ "$match": {
"_likes": { "$exists": true }
}},
{ "$project": { "likeCount": { "$size": "$_likes" } } }
]).forEach(function(doc) {
bulkOp.find({ "_id": doc._id }).updateOne({
"$set": { "likeCount": NumberInt(doc.likeCount) }
});
count++;
if (count % 200 === 0) {
// Execute per 200 operations and re-init
bulkOp.execute();
bulkOp = db.posts.initializeUnorderedBulkOp();
}
})
// Clean up queues
if (count > 0) {
bulkOp.execute();
}