查询和投影作为MongoDb中数组元素的字典值

时间:2018-10-03 12:43:01

标签: mongodb mongodb-query projection

我是MongoDB的新手,当找到另一个数组元素时,需要有关投影数组元素的帮助。

以下是我的文档的示例-

{
  "_id": ObjectId("5bab53afcfbc7829bc6356a0"), 
  "category": [
    {
      "categoryRating": 3,
      "categoryName": "Crime",
      "categoryNameNew": "Crime"
    },
    {
      "categoryRating": 4,
      "categoryName": "Security Services",
      "categoryNameNew": "Other"
    },
    {
      "categoryRating": 4,
      "categoryName": "Civil Unrest",
      "categoryNameNew": "Societal"
    },
    {
      "categoryRating": 4,
      "categoryName": "Terrorism",
      "categoryNameNew": "Terrorism"
    },
    {
      "categoryRating": 3,
      "categoryName": "Kidnapping",
      "categoryNameNew": "Terrorism"
    },
    {
      "categoryRating": 4,
      "categoryName": "Geopolitical",
      "categoryNameNew": "Geopolitical"
    }
  ], 
  "country": "Setif", 
  "apiSource": "iJET", 
  "overallScore": 4, 
  "newDate": "2017-12-28T19:52:58Z"
}

当我指定categoryRating为“犯罪”时,我想要categoryName的值。因此,在这种情况下,我需要将categoryrating打印为3。

到目前为止,我已经尝试了以下查询-

 db.RiskScore.find({"country":"Setif","category.categoryName":"Crime"},{"category.categoryRating":1})

以下是我的查询结果-

{
  "_id": ObjectId("5bab53afcfbc7829bc6356a0"),
  "category": [
    { "categoryRating": 3 },
    { "categoryRating": 4 },
    { "categoryRating": 4 },
    { "categoryRating": 4 },
    { "categoryRating": 3 },
    { "categoryRating": 4 }
  ]
}

它返回所有categoryRatings而不是仅返回categoryName为Crime的那个。请在此方面的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您快到了。您只是在投影中缺少positional $ operator

db.RiskScore.find({"country":"Setif","category.categoryName":"Crime"},{"category.$.categoryRating":1})