1

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.

1
  • You need to cursor through the output of your aggregation query and update the records one by one. Currently (as of Mongo 3.2) the aggregation framework can't be used to bulk update documents. Commented Feb 19, 2016 at 16:51

2 Answers 2

3

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);
  }
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.