mongodb - How could I sort the items of a array and update to the original document -
i want sort array records
, remove " "
, " "
items containing white space.
how aggregation.
this rough idea, not working
pipeline = [ {'$unwind': '$records'} { '$sort': "records.date": 1 } ] db[source_collection].runcommand('aggregate', pipeline: pipeline allowdiskuse: true)
sample document format
{ "_id": "0005dc158e68b0a2e4f2a8d96ca733f1", "records": [ { "date": new date("2012-12-04t08:00:00+0800"), "items": [ " ", "4659 ", "463 " ] }, { "date": new date("2012-12-01t08:00:00+0800"), "items": [ " ", "4658 " ] }, { "date": new date("2012-10-18t08:00:00+0800"), "items": [ " ", "78900 " ] }, { "date": new date("2012-08-07t08:00:00+0800"), "items": [ " ", "5230 " ] } ], "gender": "f", "birthday": new date("1990-01-01t08:00:00+0800"), "birthday_type": "d" }
for sorting records
array date
check following aggregation query :
db.collectionname.aggregate({"$unwind":"$records"},{"$sort":{"records.date":1}}).pretty()
and changing items
array value need write programming code using mongo bulk write following script update every items
array value check below :
var bulk = db.collectionname.initializeorderedbulkop(); var counter = 0; db.collectionname.find({ "records": { "$exists": true } }).foreach(function(data) { for(var ii = 0; ii < data.records.length; ii++) { var items = data.records[ii].items; var arr = []; for(var j = 0; j < items.length; j++) { arr[j] = data.records[ii].items[j].trim() } var updoc = { "$set": {} }; var updatekey = "records." + ii + ".items"; updoc["$set"][updatekey] = arr; // queue update bulk.find({ "_id": data._id }).update(updoc); counter++; // drain , re-initialize every 1000 update statements if(counter % 1000 == 0) { bulk.execute(); bulk = db.collectionname.initializeorderedbulkop(); } } }) // add rest in queue if(counter % 1000 != 0) bulk.execute();
Comments
Post a Comment