Ignasi
Ignasi

Reputation: 6185

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.

I saw it could be reached using aggregation or an additional field which stores array length.

I'm working on a kind of QueryBuilder which doesn't use aggregation, so I've choosen to add another field.

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.

Upvotes: 1

Views: 2154

Answers (2)

Maxime Beugnet
Maxime Beugnet

Reputation: 822

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.

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);
  }
)

Upvotes: 3

metame
metame

Reputation: 2640

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:

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

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

Upvotes: 1

Related Questions