MongoDB query for nested elements on each level

為{幸葍}努か 提交于 2021-01-29 08:54:01

问题


I have to find all documents in collection, also those nested, by one field that all of them have (common_field). In xpath it would be something like this: //*[@common_field='value']. How to do something like this in mongo?

{
  "_id": ObjectId(
  "5e3800700045c500cecffb00"
  ),
  "common_field": "100281",
  "other_field": "other",
  "A": {
    "common_field": "313000000",
    "a_field": "a"
  },
  "B": {
    "common_field": "213125",
    "b_field": "bb",
    "B": {
      "common_field": "543534",
      "b_field": "b"
    },
    "C": {
      "common_field": "312312",
      "c_field": "c"
    }
  }
}

回答1:


I don't think you can achieve it natively with the Aggregation framework, you have to write a recursive function. This one should work:

var CheckField = function (doc, fieldName, value) {
   var ret = false;
   Object.keys(doc).forEach(function (key) {
      if (key == fieldName && doc[key] == value) {
         ret = true;
      } else {
         if (typeof doc[key] == "object")
            ret = ret || CheckField(doc[key], fieldName, value);
      }
   });
   return ret;
};

Then use the function like this:

var ObjIds = []
db.col.find({}).forEach(function (myDoc) {
   if (CheckField(myDoc, "common_field", "313000000"))
      ObjIds.push(myDoc._id);
})

Either print documents directly of use returned array as query filter:

db.col.find({ _id: { $in: ObjIds } })


来源:https://stackoverflow.com/questions/60038857/mongodb-query-for-nested-elements-on-each-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!