MongoDB查询文档

时间:2017-05-18 14:23:33

标签: mongodb

我有一个MongoDB集合,例如Given Below

{
   "IslamabadICT": {
      "campus_name": "Islamabad",
      "campus_province": "ICT"
   },
   "KarachiSindh": {
      "campus_name": "Karachi",
      "campus_province": "Sindh"
   },
   "LahorePunjab": {
      "campus_name": "Lahore",
      "campus_province": "Punjab"
   },
   "PeshawarKPK": {
      "campus_name": "Peshawar",
      "campus_province": "KPK"
   }
}

我想查询campus_name =' Lahore'的所有文件。我正在运行以下命令

db.campus.find({" campus_name":" Lahore"})。pretty()但它什么都不返回。 MondoDB的版本是3.4,我正在运行mongo shell。

有什么建议吗?

先谢谢

1 个答案:

答案 0 :(得分:1)

以下是将文档返回campus_name='Lahore' -

的查询
db.campus.find().map( function(myDoc) { 
  for (var key in myDoc) {
    if(key != "_id" && myDoc[key].campus_name == "Lahore"){
      print( "Found it!!");
      return myDoc;
    }
  }
  return null;
} ).find(function(doc){if(doc!=null) return doc;});

除此之外,我强烈建议您重新构建文档格式。一个例子可能是按如下方式重组文件 -

{
    {
        "main": "IslamabadICT",
        "campus_name": "Islamabad",
        "campus_province": "ICT"
    },
    {
        "main": "KarachiSindh",
        "campus_name": "Karachi",
        "campus_province": "Sindh"
    },
    {
        "main": "LahorePunjab",
        "campus_name": "Lahore",
        "campus_province": "Punjab"
    },
    {
        "main": "PeshawarKPK",
        "campus_name": "Peshawar",
        "campus_province": "KPK"
    }
}

它将使查询更容易 -

db.sht.find({campus_name:"Lahore"}).pretty()

首先尝试的是哪一个。 :)