I'm writing a migration script
to update some fields of a collection, say collection2
. In our collections, we store Japanese dates with following format in each document:
"date" : { "era" : 4, "year" : 25, "month" : 11, "day" : 25 }// i.e `25-11-2014`
Now I'm looking for an easy way to get all the documents of the collection with date > 1-10-2014
ie
date > { "era" : 4, "year" : 25, "month" : 10, "day" : 1 }
Code works well, but I'm feeling like it can be optimised but don't know how.
collection1
using forEach
and extracting its date collection1.date > 1-10-2014
copy some document fields from collection2
and update them
db.col1.find({ name: x123 }).forEach(function(doc){ if(hasValidDate(doc.date1)){ db.col2.find({col1_id:doc._id}).forEach(function(doc2){ var copyobj = {doc2.x1, doc2.x2, ...}; db.col2.update({col1_id:doc._id}, copyobj); }); } }); function hasValidDate(date){ return (date.era == 4 && date.year >= 26 && (date.month >= 10 && date.day >= 1))?true:false; }
You could try including the actual date filtering within your find()
query:
db.col1.find(
{
"name": "x123",
"date.era": 4,
"date.year": { "$gte": 26 },
"date.month": { "$gte": 10 },
"date.day": { "$gte": 1 },
}
).forEach(function(doc){
var copyobj = { "$set": {"x1": "1", "x2": "3", ...} };
db.col2.update({_id: doc._id}, copyobj);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.