当父字段未知时,在嵌套文档中查找具有字段的记录 [英] Find records with field in a nested document when parent fields are not known

查看:34
本文介绍了当父字段未知时,在嵌套文档中查找具有字段的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于包含如下文档的集合,我需要找到特定字段所在的文档 - 例如.lev3_field2(在下面的文档中)存在.

With a collection with documents like below, I need to find the documents where a particular field - eg. lev3_field2 (in document below) is present.

我尝试了以下操作,但没有返回任何结果,尽管某些文档中存在 lev3_field2 字段.

I tried the following, but this doesn't return any results, though the field lev3_field2 is present in some documents.

db.getCollection('some_collection').find({"lev3_field2": { $exists: true, $ne: null } })

{
    "_id" : ObjectId("5884de15bebf420cf8bb2857"),
    "lev1_field1" : "139521721",
    "lev1_field2" : "276183",
    "lev1_field3" : {
        "lev2_field1" : "4",
        "lev2_field2" : {
            "lev3_field1" : "1",
            "lev3_field2" : {
                "lev4_field1" : "1",
                "lev4_field2" : "1"
            },
            "lev3_field3" : "5"
        },
        "lev2_field3" : {
            "lev3_field3" : "0",
            "lev3_field4" : "0"
        }
    }
}

update1:这是一个示例,但是在实际文档中,不知道要查找的字段的父字段是什么.因此,我会寻找 `levM_fieldN' 而不是 lev3_field2 .

update1: this is an example, however in the real document it is not known what the parent fields are for the field to look for. So instead of lev3_field2 , I would be looking for `levM_fieldN'.

update2:速度对我来说不是主要问题,我也可以使用相对较慢的选项,因为主要功能是查找具有讨论标准的文档,一旦文档被找到并理解架构后,可以通过包含父键来重写查询以提高性能.

update2: Speed is not a primary concern for me, I can work with relatively a bit slower options as well, as the primary function is to find documents with the criteria discussed and once the document is found and the schema is understood, the query can be re-written for performance by including the parent keys.

推荐答案

要在嵌套文档中搜索一个键,您需要递归地迭代文档字段,您可以在 JavaScript 中借助 $where 方法以下查询将搜索文档及其子文档中是否存在键名.

To search a key in nested document you need to iterate the documents fields recursively, you can do this in JavaScript by the help of $where method in MongoDB The below query will search if a key name exists in a documents and its subdocuments.

我已经用你给出的例子检查了这个,它工作得很好.

I have checked this with the example you have given, and it is working perfectly fine.

db.getCollection('test').find({ $where: function () {
    var search_key = "lev3_field2";

    function check_key(document) {
      return Object.keys(document).some(function(key) {
        if ( typeof(document[key]) == "object" ) {
            if ( key == search_key ) {
                return true;
            } else {
                return check_key(document[key]);
            }
        } else {
          return ( key == search_key );
        }
      });
    }
    return check_key(this);
  }}

);

这篇关于当父字段未知时,在嵌套文档中查找具有字段的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆