查询每个级别的嵌套元素

查询每个级别的嵌套元素

本文介绍了MongoDB 查询每个级别的嵌套元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过一个字段(common_field)找到集合中的所有文档,包括嵌套的文档.在 xpath 中,它会是这样的://*[@common_field='value'].如何在 mongo 中做这样的事情?

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"
    }
  }
}

推荐答案

我不认为你可以用聚合框架本地实现它,你必须编写一个递归函数.这个应该可以工作:

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

然后像这样使用函数:

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

这篇关于MongoDB 查询每个级别的嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:23