在特定条件下以嵌套级别收集不同的字段名称 [英] Collect distinct field names at nested level with specific condition

查看:82
本文介绍了在特定条件下以嵌套级别收集不同的字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题陈述,其中我需要"config.first.second"子级别的所有字段名称,其中include字段至少为true. 这是我的mongo收集对象.

I have problem statement, in which i need all the field names at child level of "config.first.second" where include field is true at least once. Here is my mongo collection objects.

   [ {
        "_id" : ObjectId("560e97f4a78eb445cd2d75e5"),
        "config" : {
            "first" : {
                "second" : {
                    "field1" : {
                       "include":"true"
                    },
                    "field3" : {
                      "include":"true"
                    },
                    "field9" : {
                        "include":"false"
                    },
                    "field6" : {
                        "include":"false"
                    }
                }
            }
        },
        "date_created" : "Fri Oct 02 14:43:00 UTC 2015",
        "last_updated" : "Mon Apr 11 15:26:37 UTC 2016",
        "id" : ObjectId("560e97f4a78eb445cd2d75e5")
    },
    {
        "_id" : ObjectId("56154465a78e41c04692af20"),
        "config" : {
            "first" : {
                "second" : {
                    "field1" : {
                        "include":"true"
                    },
                    "field3" : {
                        "include":"false"
                    },
                    "field7" : {
                    "include":"true"
                    }
                }
            }
        },
        "date_created" : "Wed Oct 07 16:12:21 UTC 2015",
        "last_updated" : "Mon Apr 11 15:18:58 UTC 2016",
        "id" : ObjectId("56154465a78e41c04692af20")
    }
]

使用以上mongo集合.查询必须返回结果

Using above mongo collection . Query must return result

["field1","field3","field7"]

推荐答案

您可以使用mapReduce运行:

You can run with mapReduce:

db.collection.mapReduce(
  function() {
    Object.keys(this.config.first.second)
      .filter( k => this.config.first.second[k].include === "true" )
      .forEach(k => emit(k,1) );
  },
  function() { },
  { 
    "out": { "inline": 1 },

  }
)['results'].map( d => d._id )

如果您拥有MongoDB 3.4,则可以使用.aggregate():

If you have MongoDB 3.4 then you can use .aggregate():

db.collection.aggregate([
  { "$project": {
    "field": {
      "$filter": {
        "input": { "$objectToArray": "$config.first.second" },
        "as": "f",
        "cond": { "$eq": [ "$$f.v.include", "true" ] }
      }
    }
  }},
  { "$unwind": "$field" },
  { "$group": { "_id": "$field.k" } }
]).toArray().map(d => d._id)

返回:

[
    "field1",
    "field3",
    "field7"
]

这篇关于在特定条件下以嵌套级别收集不同的字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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