3

我有一份文件——

  {"_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"})会给我任何子字段具有“必需”价值的所有文件

4

3 回答 3

5

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

 {"_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})
于 2013-04-04T04:51:15.850 回答
0

您可以通过db.foo.find({ 'status.algo1' : 'required' })or进行搜索db.foo.find({ 'status.algo2' : 'required' }),但可能无法通过 regex 进行过滤keys,另请参阅这篇文章:https ://stackoverflow.com/a/7290728/654952

于 2013-03-07T11:09:56.903 回答
0

您可以使用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;
    }
}

这有帮助吗?

干杯

罗纳德

于 2013-03-22T17:23:48.140 回答