我有一组用户,每个用户可以订阅一个或多个服务.每个服务都有一些元数据,包括用户对该服务的信用数量.
如果我无法知道服务对象密钥是什么,如何找到某些服务少于50个学分的所有用户对象?
从概念上讲,它会是这样的,它不起作用:
db.users.find({services.*.credits : {$lt : 50}})
Run Code Online (Sandbox Code Playgroud)
用户集合:
{
_id: 4f0ea25072139e4d2000001f,
services : {
a : { credits : 100, score : 2000 },
b : { credits : 200, score : 300 },
c : { credits : 10, score : 1300 }
}
},
{
_id: 4f0ea25072139e4d2000001f,
services : {
f : { credits : 68, score : 14 },
q : { credits : 1000, score : 102 },
z : { credits : 59, score : 352 }
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的另一个例子,如果在这里不清楚,将在这里解释:http://www.mongodb.org/display/DOCS/Advanced+Queries#comment-346075854
Com*_*ast 20
这是您问题的实际答案.
如果您无法知道服务对象键的内容,您可以如何找到某些服务少于50个学分的所有用户对象,如下所示.
使用$ where查询:
db.users.find({
$where: function () {
for (var index in this.services)
if (this.services[index].credits < 50)
return this;
}
});
Run Code Online (Sandbox Code Playgroud)
Eve*_*man -4
我认为如果将该服务对象放入数组中会更容易,因此您可以使用$elemMatch,例如:
{
services : [
{key: "a" , credits : 100, score : 2000 },
{key: "b", credits : 200, score : 300 },
{key: "c", credits : 10, score : 1300 }
]
}
Run Code Online (Sandbox Code Playgroud)
和
{
_id: 4f0ea25072139e4d2000001f,
services : [
{key: "f", credits : 68, score : 14 },
{key: "q", credits : 1000, score : 102 },
{key: "z", credits : 59, score : 352 }
]
}
Run Code Online (Sandbox Code Playgroud)
那么您将编写的查询将如下所示:
db.coll.find({services: {$elemMatch : {credits: {$lt: 50}}}});
Run Code Online (Sandbox Code Playgroud)
结果:
{ "_id" : ObjectId("4f0f2be07561bf94ea47eec4"), "services" : [ { "key" : "a", "credits" : 100, "score" : 2000 }, { "key" : "b", "credits" : 200, "score" : 300 }, { "key" : "c", "credits" : 10, "score" : 1300 } ] }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9482 次 |
| 最近记录: |