Mongodb dot notation wildcard?

后端 未结 3 2014
自闭症患者
自闭症患者 2020-12-10 01:22

I have a collection of users, each of which may be subscribed to one or more services. Each service has some meta data, including the number of credits the user has for that

3条回答
  •  忘掉有多难
    2020-12-10 01:43

    I think it would be easier if you put that services object into an array, so you can use $elemMatch, like:

    {
      services : [
        {key: "a" , credits : 100, score : 2000 },
        {key: "b", credits : 200, score : 300 },
        {key: "c", credits : 10, score : 1300 }
      ]
    }
    

    and

    {
      _id: 4f0ea25072139e4d2000001f,
      services : [
        {key: "f", credits : 68, score : 14 },
        {key: "q", credits : 1000, score : 102 },
        {key: "z", credits : 59, score : 352 }
      ]
    }
    

    Then the query you would write would be like this:

    db.coll.find({services: {$elemMatch : {credits: {$lt: 50}}}});
    

    result:

    { "_id" : ObjectId("4f0f2be07561bf94ea47eec4"), "services" : [  {   "key" : "a", "credits" : 100, "score" : 2000 }, { "key" : "b", "credits" : 200, "score" : 300 },    {   "key" : "c",    "credits" : 10,     "score" : 1300 } ] }
    

提交回复
热议问题