MongoDB 查询文档

  • 查询文档

    在本章中,我们将学习如何从MongoDB集合中查询文档。
  • find()方法

    要查询MongoDB集合中的数据,您需要使用MongoDB的find()方法。
    语法
     
    >db.COLLECTION_NAME.find([query],[projection])
    
    参数
    • query - document [可选的]。使用查询操作符指定选择筛选器。若要返回集合中的所有文档,请省略此参数或传递一个空文档({})。
    • projection -document [可选的]。指定要在文档中返回与查询筛选器匹配的字段。要返回匹配文档中的所有字段,请省略此参数。有关详细信息,请参见投影
    示例
    假设我们已经创建了一个名为mycol的集合-
     
    > use sampleDB
    switched to db sampleDB
    > db.createCollection("mycol")
    { "ok" : 1 }
    >
    
    并使用insert()方法在其中插入3个文档,如下所示-
     
    db.mycol.insert([
      {
        title: "MongoDB Overview",
        description: "MongoDB is no SQL database",
        by: "蝴蝶教程",
        url: "https://www.jc2182.com",
        tags: ["mongodb", "database", "NoSQL"],
        likes: 100
      },
      {
        title: "NoSQL Database",
        description: "NoSQL database doesn't have tables",
        by: "蝴蝶教程",
        url: "https://www.jc2182.com",
        tags: ["mongodb", "database", "NoSQL"],
        likes: 20,
        comments: [
          {
            user:"user1",
            message: "My first comment",
            dateCreated: new Date(2013,11,10,2,35),
            like: 0
          }
        ]
      }
    ])
    
    以下方法检索集合中的所有文档-
     
    db.mycol.find()
    { "_id" : ObjectId("5f474d67f4d867c5a4de6189"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "蝴蝶教程", "url" : "https://www.jc2182.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
    { "_id" : ObjectId("5f474d67f4d867c5a4de618a"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "蝴蝶教程", "url" : "https://www.jc2182.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T18:35:00Z"), "like" : 0 } ] }
    
  • pretty() 方法

    要以格式化的方式显示结果,可以使用pretty()方法。
    语法
     
    >db.COLLECTION_NAME.find().pretty()
    
    以下示例从名为mycol的集合中检索所有文档,并以易于阅读的格式排列它们。
     
    > db.mycol.find().pretty()
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de6189"),
      "title" : "MongoDB Overview",
      "description" : "MongoDB is no SQL database",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 100
    }
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de618a"),
      "title" : "NoSQL Database",
      "description" : "NoSQL database doesn't have tables",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 20,
      "comments" : [
        {
          "user" : "user1",
          "message" : "My first comment",
          "dateCreated" : ISODate("2013-12-09T18:35:00Z"),
          "like" : 0
        }
      ]
    }
    
    
  • findOne()方法

    除了find()方法之外,还有findOne()方法,该方法仅返回一个文档。
    语法:
    
    >db.COLLECTIONNAME.findOne()
    
    以下示例检索title为MongoDB Overview的文档。
     
    db.mycol.findOne({title: "MongoDB Overview"})
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de6189"),
      "title" : "MongoDB Overview",
      "description" : "MongoDB is no SQL database",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 100
    }
    
  • >RDBMS(关系型数据库系统)中MongoDB中的子句等效

    操作 例子 语法 RDBMS等效
    相等 {<key>:{$eg;<value>}} db.mycol.find({"by":"蝴蝶教程"}).pretty() where by = '蝴蝶教程'
    小于 {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50
    小于等于 {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50
    大于 {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50
    大于等于 {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50
    不相等 {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50
    值在数组中 {<key>:{$in:[<value1>, <value2>,……<valueN>]}} db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty() where name matches any of the value in :["Raj", "Ram", "Raghu"]
    值不在数组中 {<key>:{$nin:<value>}} db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty() where name values is not in the array :["Ramu", "Raghav"] or, doesn’t exist at all
  • MongoDB中的AND

    要基于AND条件查询文档,您需要使用$and关键字。以下是AND的基本语法-
    语法:
    
    >db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
    
    以下示例将显示所有由“蝴蝶教程”编写的教程,其标题为“MongoDB Overview”。
     
    db.mycol.find({$and:[{"by":"蝴蝶教程"},{"title": "MongoDB Overview"}]}).pretty()
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de6189"),
      "title" : "MongoDB Overview",
      "description" : "MongoDB is no SQL database",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 100
    }
    
    对于上面给出的示例,等效的where子句将是“where by ='蝴蝶教程'AND title ='MongoDB Overview''。您可以在find子句中传递任意数量的键,值对。
  • MongoDB中的OR

    要基于OR条件查询文档,您需要使用$or关键字。以下是OR的基本语法-
    语法:
    
    >db.mycol.find({ $or: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
    
    以下示例将显示所有由“蝴蝶教程”编写或标题为“MongoDB Overview”的教程。
     
    db.mycol.find({$or:[{"by":"蝴蝶教程"},{"title": "MongoDB Overview"}]}).pretty()
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de6189"),
      "title" : "MongoDB Overview",
      "description" : "MongoDB is no SQL database",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 100
    }
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de618a"),
      "title" : "NoSQL Database",
      "description" : "NoSQL database doesn't have tables",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 20,
      "comments" : [
        {
          "user" : "user1",
          "message" : "My first comment",
          "dateCreated" : ISODate("2013-12-09T18:35:00Z"),
          "like" : 0
        }
      ]
    }
    
  • 一起使用AND和OR

    下面的示例将显示likes大于10且title为“MongoDB Overview”或by为“蝴蝶教程”的文档。等价的SQL where子句为'where likes> 10 AND(by ='蝴蝶教程'OR title ='MongoDB Overview')
     
    db.mycol.find({"likes": {$gt:10}, $or: [{"by": "蝴蝶教程"},{"title": "MongoDB Overview"}]}).pretty()
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de6189"),
      "title" : "MongoDB Overview",
      "description" : "MongoDB is no SQL database",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 100
    }
    {
      "_id" : ObjectId("5f474d67f4d867c5a4de618a"),
      "title" : "NoSQL Database",
      "description" : "NoSQL database doesn't have tables",
      "by" : "蝴蝶教程",
      "url" : "https://www.jc2182.com",
      "tags" : [
        "mongodb",
        "database",
        "NoSQL"
      ],
      "likes" : 20,
      "comments" : [
        {
          "user" : "user1",
          "message" : "My first comment",
          "dateCreated" : ISODate("2013-12-09T18:35:00Z"),
          "like" : 0
        }
      ]
    }
    
  • MongoDB中的NOR

    要根据NOT条件查询文档,需要使用$not关键字。以下是NOT的基本语法-
     
    >db.COLLECTION_NAME.find({$not: [{key1: value1}, {key2:value2}]})
    
    假设我们在集合empDetails中插入了3个文档,如下所示-
    
    db.empDetails.insertMany(
      [
        {
          First_Name: "Radhika",
          Last_Name: "Sharma",
          Age: "26",
          e_mail: "radhika_sharma.123@gmail.com",
          phone: "9000012345"
        },
        {
          First_Name: "Rachel",
          Last_Name: "Christopher",
          Age: "27",
          e_mail: "Rachel_Christopher.123@gmail.com",
          phone: "9000054321"
        },
        {
          First_Name: "Fathima",
          Last_Name: "Sheik",
          Age: "24",
          e_mail: "Fathima_Sheik.123@gmail.com",
          phone: "9000054321"
        }
      ]
    )
    
    以下示例将检索first_name不是“Radhika”或者last_name不是“Christopher”的文档
    
    db.empDetails.find( { $nor:[{"First_Name": "Radhika"}, {"Last_Name": "Christopher"} ] }).pretty();
    {
      "_id" : ObjectId("5f486da720f2c31cceb9e491"),
      "First_Name" : "Fathima",
      "Last_Name" : "Sheik",
      "Age" : "24",
      "e_mail" : "Fathima_Sheik.123@gmail.com",
      "phone" : "9000054321"
    }
    
  • MongoDB中的NOT

    要根据NOT条件查询文档,您需要使用$ not关键字,这是NOT的基本语法-
     
    db.COLLECTION_NAME.find({$NOT: [{key1: value1}, {key2:value2}]})
    
    以下示例将检索年龄不超过25岁的文档-
    
    db.empDetails.find( { "Age": { $not: { $gt: "25" } } } ).pretty();
    {
      "_id" : ObjectId("5f486da720f2c31cceb9e491"),
      "First_Name" : "Fathima",
      "Last_Name" : "Sheik",
      "Age" : "24",
      "e_mail" : "Fathima_Sheik.123@gmail.com",
      "phone" : "9000054321"
    }