【问题标题】:Mongo Query on SubfieldsMongo 查询子字段
【发布时间】:2013-02-22 11:12:09
【问题描述】:

我有一个文件-

  {"_id" : ObjectId("51385d2308d427ce306f0100"),
  "aid" : "1",
  "studyId" : "study-1",
  "mediaType" : "microBlog",
  "text" : "bla bla",
  "sentences" : "bla bla",
  "status" : {
          "algo1" : "required",
          "algo2" : "required",
          "algo3" : "completed",
          "algo4" : "completed"
  },
  "priority" : "u"}

状态字段有多个具有不同状态值的子字段。是否可以创建一个查询以返回所有状态子字段的值为“必需”的文档?

db.foo.find({status : "required"}) 这样的东西会给我所有子字段具有“必需”值的文档

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您可以通过db.foo.find({ 'status.algo1' : 'required' })db.foo.find({ 'status.algo2' : 'required' }) 进行搜索,但可能无法通过正则表达式keys 进行过滤,另请参阅此帖子:https://stackoverflow.com/a/7290728/654952

    【讨论】:

    • 是的,我需要为每个 status.algo 使用 or 条件,因为我所需要的在 Mongo 中是不可能的。
    【解决方案2】:

    您可以使用mapReduce(),其中 map() 函数将包含以下内容:

    // loop all key/value pairs in status without knowing its key
    for ( item in this.status ) {
        // if value is required: emit the data and break the loop
        if ( this.status[item] == "required" ) {
            emit( ... )
            break;
        }
    }
    

    这有帮助吗?

    干杯

    罗纳德

    【讨论】:

      【解决方案3】:

      另一种更有效的方法是将“状态”子文档实现为“类型值”数组,如下所示:

       {"_id" : ObjectId("51385d2308d427ce306f0100"),
        "aid" : "1",
        "studyId" : "study-1",
        "mediaType" : "microBlog",
        "text" : "bla bla",
        "sentences" : "bla bla",
        "status" : [
                { type: "algo1", value: "required" },
                { type: "algo2", value: "required" },
                { type: "algo3", value: "completed" },
                { type: "algo4", value: "completed" }
        ],
        "priority" : "u"}
      

      这将允许您使用以下查询查找所有子字段的值为“必需”的所有文档:

      db.foo.find({"status.value":"required"})
      

      在这个子字段上定义索引会加快查询速度:

      db.foo.ensureIndex({"status.value":1})
      

      【讨论】:

        猜你喜欢
        • 2015-03-10
        • 2013-05-20
        • 1970-01-01
        • 1970-01-01
        • 2017-02-19
        • 2014-01-29
        • 1970-01-01
        • 2013-09-12
        • 2017-06-15
        相关资源
        最近更新 更多