简体   繁体   English

MongoDB查找查询优化

[英]Mongodb find query optimization

I'm writing a migration script to update some fields of a collection, say collection2 . 我正在编写一个migration script来更新集合的某些字段,例如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 > 1-10-2014的馆藏的所有文档,即

 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. 代码运行良好,但我感觉可以对其进行优化,但不知道如何做。

  • iterating collection1 using forEach and extracting its date 使用forEach迭代collection1并提取其日期
  • check date collection1.date > 1-10-2014 检查日期collection1.date > 1-10-2014日期collection1.date > 1-10-2014
  • copy some document fields from collection2 and update them collection2复制一些文档字段并更新它们

     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: 您可以尝试在find()查询中包括实际的日期过滤:

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

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

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