MongoDB - 查询文档

在本章中,我们将学习如何从MongoDB集合中查询文档.

find()方法

从MongoDB查询数据集合,你需要使用MongoDB的 find()方法.

语法

find的基本语法()方法如下 :

 
>db.COLLECTION_NAME.find()


find()方法将以非结构化的方式显示所有文档.

pretty()方法

要以格式化方式显示结果,可以使用漂亮()方法.

语法

 
>db.mycol.find().pretty()


示例

>db.mycol.find().pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.it1352.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>


除了find()方法之外,还有 findOne()方法,它只返回一个文档.

RDBMS MongoDB中的子句等价物

要根据某些条件查询文档,可以使用以下操作.

操作语法示例RDBMS等价
Equality{< key>: < value>}db.mycol.find({"by":"it1352"}).pretty()where by ='it1352'
Less Than{< key>: {$ lt:< value>}}db.mycol.find({"likes":{$ lt:50}}).pretty()where likes<50
Less Than Equals{< key>:{$ lte:< value>}}db.mycol.find({"likes":{$ lte:50}}).pretty()where likes<=50
Greater Than{< key>:{$ gt:< value>}}db.mycol.find({"likes":{$ gt:50} }).pretty()where likes>50
Greater Than Equals{< key>:{$ gte :< value>}}db.mycol.find({"likes":{$ gte:50}}).pretty()where likes>=50
Not Equals{< key>:{$ ne:< value>}}db.mycol.find({"likes":{$ ne:50}}).pretty()where likes!=50

AND MongoDB

语法

find()方法中,如果通过','分隔多个键,则MongoDB将其视为条件.以下是 AND :

>db.mycol.find(
   {
      $and: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()


示例

以下示例将显示由'tutorials point'编写的所有教程,其标题为'MongoDB Overview'.

>db.mycol.find({$and:[{"by":"it1352"},{"title": "MongoDB Overview"}]}).pretty() {
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.it1352.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}


对于上面给出的例子,等效的where子句将是'where by ='it1352'AND title ='MongoDB Overview''.您可以在find子句中传递任意数量的键值对.

或者在MongoDB中

语法

要根据OR条件查询文档,您需要使用 $或关键字.以下是 OR :

>db.mycol.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()


示例

以下示例将显示由'it1352'编写的所有教程或其标题为'MongoDB Overview'.

>db.mycol.find({$or:[{"by":"it1352"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.it1352.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>


一起使用AND和OR

示例

以下示例将显示喜欢大于10且标题为"MongoDB概述"或"教程点"的文档.等效SQL where子句'where likes>10 AND (by = 'it1352' OR title = 'MongoDB Overview')'

>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "it1352"},
   {"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.it1352.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>