【问题标题】:Mongodb - Query embedded object with variable keyMongodb - 使用变量键查询嵌入对象
【发布时间】:2017-02-13 22:16:14
【问题描述】:

我有一个带有以下对象的 Mongo DB:

"clients" : {
    "x" : {
        "clientId" : "x1",
        "mainInfo" : {
                       ...
        },
        "events" : 
            {
            "58a176bbc3588410cd5450c6" : {
                "clientType" : "5001",
                "location" : "60001"
                }
            "58a176bbc3588410cd5450c8" : {
                "clientType" : "5001",
                "location" : "60002"
                }
                  ....}

我似乎无法弄清楚如何查询 'clients.x.events.(variable id).clientType' = 50001 的位置。有没有办法深入事件嵌入对象以获取匹配“clientType”的所有记录:“5001”?

谢谢

【问题讨论】:

  • 不幸的是,这是不可能的。考虑将events 字段转换为数组,这样查询会容易得多。

标签: mongodb


【解决方案1】:

您需要创建如下所示的键值对对象。

var variable_id = <your variable id>;
db.collection.find({ [ 'clients.x.events.'+variable_id+'.clientType' ]:5001 });

阅读更多关于这个here

【讨论】:

    【解决方案2】:

    也许你可以使用$where 运算符。它对我有用。

    使用 $where 运算符传递包含 查询的 JavaScript 表达式或完整的 JavaScript 函数 系统。

    db.collection.find({"$where" : function(){ 
        for( var c in this ){
            if( c == "x" ){ 
                for(var i in this[c]){ 
                     for(var j in this[c][i]){
                          if(j == 'clientType' && this[c][i][j] == '5001'){
                               return true;
                          }
                     }
                 }
            };
         }
         return false; 
    }});
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2018-07-14
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多