0

我有問題語句,其中我需要在「config.first.second」子級別的所有字段名稱,其中include字段至少爲一次。 這是我的mongo集合對象。收集具有特定條件的嵌套級別不同的字段名稱

[ { 
     "_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集合。查詢必須返回結果

["field1","field3","field7"] 
+0

這是一個可怕的結構與absol美好的沒有實用程序來查詢。你需要通過JavaScript遞歸來做任何事情。結構需要改變,因爲這不僅僅是你使用數據庫的原因。如果您認爲這是您想要的結構,請使用XML文檔存儲。 –

+0

可能是但不能改變。這是否像我只能循環。不是一個好的解決方案。嘗試投影像這樣db.getCollection('my_collection')。aggregate([{$ project:{result:「$ config.first.second」}}])但不起作用 –

+0

您不能使用聚合或任何標準查詢條件。僅mapReduce。 –

回答

1

你可以用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()

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" 
] 
相關問題