Mongodb点符号通配符?

stu*_*lue 22 syntax mongodb

我有一组用户,每个用户可以订阅一个或多个服务.每个服务都有一些元数据,包括用户对该服务的信用数量.

如果我无法知道服务对象密钥是什么,如何找到某些服务少于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)

  • 他问道,"如果我无法知道服务对象密钥是什么,我怎样才能找到一些服务少于50个学分的用户对象?" 我回答了他的问题.我并没有将答案归结为"回答者",因为它们不是答案.他们是那些人说"你不能/不应该这样做",显然你可以,而且这是一个纯粹的意见问题,你是否应该这样做.我不同意"没有理由使用这样的数据结构"......有很多很好的理由这样做.只是因为你不了解它们,不是我的错,也不是我的错. (9认同)
  • 我不看人们的代表我只是看了答案.我不怀疑你对MongoDB的了解比我更多.但是,如果它不是问题的答案,那么我就不得不向它投票; 我不会因为你有很高的代表而不这样做.告诉别人没有办法做某事,实际上有,并不酷.告诉人们他们的数据结构只是因为你没有看到它的意义而毫无意义,也不是很酷.也许他们有一个很好的理由使用它你根本不理解.也许你问过你可能会学到什么. (4认同)
  • 我完全同意@CommaToast在这里所说的话.我需要运行一次性查询来确定数据库中是否缺少某些数据以确定是否需要进行代码更改.数据库已经存在,数据结构没有任何问题.我无法更新预先存在的数据结构来追踪一些小问题.建议这样做有利于提供一个实际的解决方案是明显的无知. (3认同)

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)

  • -1,因为这不是问题的答案。并非每个人都有能力更改他们正在使用的数据的架构。这个问题仍然没有答案。 (19认同)