如何从mongodb中的嵌套对象获取密钥

时间:2016-07-25 10:11:12

标签: mongodb

我正在从mongodb迁移到mysql。我在一个集合中有一个子文档,我需要使用子文档找到数据。

集合结构如下所示

{
        "_id" : ObjectId("578506a90420bec15ea33783"),
        "reselected" : "ABCDEFGH",
            "reskip" : [],
            "restatus" : "active",
            "reuser" : {
                "activeListings" : [ 
                    {
                        "subcategory" : "mobiles",
                        "title" : " Mobile 1",
                        "transactiontype" : "post"
                    }, 
                    {
                        "category" : "mobiles",
                        "title" : " Mobile 2",
                        "transactiontype" : "post"
                    } ],
            "reuserInput" : "2",
            "reussdsession" : "303757117"   }

我尝试过使用mapreduce代码

mr = db.runCommand({
          "mapreduce" : "collection name",
          "map" : function() {     */map/
            for (var key in "this.reuser.activeListings") { 
            for (var key1 in "this.reuser.activeListings"[key]) { 
                emit(key1, null); 
            }
            }
          },
          "reduce" : function(key, stuff) { return null; },  /*reducer/
          "out": "my_collection" + "_keys"
        })

我需要输出activeListings

{subcategory,title,transactiontype,category}

1 个答案:

答案 0 :(得分:0)

您基本上需要迭代数组然后发出每个键。以下mapReduce脚本将为您提供所需的键列表:

mr = db.runCommand({
    "mapreduce": "collectionName",
    "map": function() { /* mapper */
        this.reuser.activeListings.forEach(function (obj){
            for (var key in obj) { emit(key, null); }
        });                
    },
    "reduce": function() {}, /* reducer */
    "out": "my_collection" + "_keys"
})

要获取所有动态键的列表,请在生成的集合上运行distinct:

> db[mr.result].distinct("_id")
["subcategory", "title", "transactiontype", "category"]