简体   繁体   English

MongoDB文档具有用于计数数组元素的字段

[英]MongoDB document with field to count elements of array

Given a MongoDB collection of documents which contains an array of whatever, would be nice to can sort the documents by the length of its array. 给定一个MongoDB文档集合,其中包含一个数组,可以按数组的长度对文档进行排序。

I saw it could be reached using aggregation or an additional field which stores array length. 我看到可以使用aggregation或存储数组长度的其他字段来达到此目的。

I'm working on a kind of QueryBuilder which doesn't use aggregation , so I've choosen to add another field. 我正在开发一种不使用aggregationQueryBuilder ,因此我选择添加另一个字段。

So I need a migration script to updates all documents of the collection in order to add a field with the length of the array of each document. 因此,我需要一个迁移脚本来更新集合的所有文档,以便添加具有每个文档数组长度的字段。

This update can be realized with one update operation over all collections? 可以通过对所有集合执行一次更新操作来实现此更新吗? How? 怎么样? I tried aggregation for that, and I get the length of each array of each document, but I don't know how to use to update documents. 我为此尝试了aggregation ,并获得了每个文档的每个数组的长度,但是我不知道如何使用它来更新文档。

I tested this on one of my collection and it works fine. 我在我的一个收藏夹上对此进行了测试,效果很好。

"comments" is an array of whatever. “评论”是一个数组。 The size of the array is in "comments_size" after the save. 保存后,数组的大小为“ comments_size”。

Just make sure you don't have any concurrency writes during this operation. 只要确保您在此操作期间没有任何并发​​写入即可。

db.posts.find({}).forEach(
  function(doc) {
    var size = doc.comments.length;
    doc.comments_size = size;
    db.posts.save(doc);
  }
)

As is mentioned in the comments, you can use the cursor returned from aggregation to update docs one by one. 如评论中所述,您可以使用聚合返回的游标来逐一更新文档。 Here's a quick example of how it could be done in the shell: 这是一个如何在shell中完成的简单示例:

var cursor = db.collection.aggregate([{ 
    $group: { 
                "_id": "$id", 
                arrayLength: { $size: "$array" } 
    }
}]);

cursor.forEach( function(doc) { 
    db.collection.update({ 'id': doc.id },{ arrayLength: doc.arrayLength }); 
});

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

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