Mongo子字段查询 [英] Mongo Query on Subfields
问题描述
我有一个文档-
{"_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"}
状态字段具有多个具有不同状态值的子字段.是否可以创建查询以返回所有状态"子字段值为必需"的所有文档?
The status field has multiple sub-fields with different status values. Is it possible to create a query such that it returns all documents for which any of the status sub-field's value is "required"?
类似于db.foo.find({status : "required"})
的东西,它将为我提供所有子字段具有必需"值的所有文档
Something like db.foo.find({status : "required"})
which would give me all documents for which any of the sub-field has value "required"
推荐答案
另一种更有效的方法是将状态"子文档实现为类型化值"数组,例如:
Another, more efficient, approach would be to implement your "status" sub-document as an array of "typed values", like this:
{"_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"}
使用此查询,您可以找到所有子字段中任何一个字段值为"required"的文档:
This would allow you to find all the documents, for which any of the sub-field has value "required", with this query:
db.foo.find({"status.value":"required"})
在此子字段上定义索引将加快查询速度:
Defining an index on this sub-field would speed up the query:
db.foo.ensureIndex({"status.value":1})
这篇关于Mongo子字段查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!