Mongodb 简明教程

MongoDB - Query Document

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

The find() Method

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

Syntax

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

>db.COLLECTION_NAME.find()

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

Example

假设我们创建了一个名为 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: "tutorials point",
		url: "http://www.tutorialspoint.com",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
		title: "NoSQL Database",
		description: "NoSQL database doesn't have tables",
		by: "tutorials point",
		url: "http://www.tutorialspoint.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("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>

The pretty() Method

要以格式化方式显示结果,可以使用 pretty() 方法。

Syntax

>db.COLLECTION_NAME.find().pretty()

Example

以下示例从名为 mycol 的集合中检索所有文档,并以易于阅读的格式对其进行排列。

> db.mycol.find().pretty()
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
	"title" : "MongoDB Overview",
	"description" : "MongoDB is no SQL database",
	"by" : "tutorials point",
	"url" : "http://www.tutorialspoint.com",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
	"title" : "NoSQL Database",
	"description" : "NoSQL database doesn't have tables",
	"by" : "tutorials point",
	"url" : "http://www.tutorialspoint.com",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 20,
	"comments" : [
		{
			"user" : "user1",
			"message" : "My first comment",
			"dateCreated" : ISODate("2013-12-09T21:05:00Z"),
			"like" : 0
		}
	]
}

The findOne() method

除了 find() 方法外,还有 findOne() 方法,仅返回一个文档。

Syntax

>db.COLLECTIONNAME.findOne()

Example

以下示例检索标题为 MongoDB Overview 的文档。

> db.mycol.findOne({title: "MongoDB Overview"})
{
	"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
	"title" : "MongoDB Overview",
	"description" : "MongoDB is no SQL database",
	"by" : "tutorials point",
	"url" : "http://www.tutorialspoint.com",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}

RDBMS Where Clause Equivalents in MongoDB

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

Operation

Syntax

Example

RDBMS Equivalent

Equality

{<key>:{$eg;<value>}}

db.mycol.find({"by":"tutorials point"}).pretty()

其中 by = 'tutorials point'

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

Values in an array

{<key>:{$in:[<value1>, <value2>,……<valueN>]}}

db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty()

其中 name 可匹配 :["Raj", "Ram", "Raghu"] 中的任何一个值

不在数组中的值

{<key>:{$nin:<value>}}

db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty()

当 name 值不在数组 :["Ramu", "Raghav"] 中,或根本不存在时

AND in MongoDB

Syntax

要基于 AND 条件查询文档,您需要使用 $and 关键字。以下是 AND 的基本语法 −

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

Example

以下示例将显示所有由“教程点”编写的教程,其标题为“MongoDB 概述”。

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

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

OR in MongoDB

Syntax

要基于 OR 条件查询文档,您需要使用 $or 关键字。以下是 OR 的基本语法 −

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

Example

以下示例将显示所有由“教程点”编写的教程,或其标题为“MongoDB 概述”的教程。

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

Using AND and OR Together

Example

以下示例将显示喜欢次数大于 10,且其标题为“MongoDB 概述”或作者为“教程点”的文档。等效的 SQL where 子句是 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'

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

NOR in MongoDB

Syntax

要基于 NOT 条件查询文档,您需要使用 $not 关键字。以下是 NOT 的基本语法 −

>db.COLLECTION_NAME.find(
	{
		$not: [
			{key1: value1}, {key2:value2}
		]
	}
)

Example

假设我们在集合 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"
		}
	]
)

以下示例将检索名字不是“Radhika”,姓氏不是“Christopher”的文档

> db.empDetails.find(
	{
		$nor:[
			40
			{"First_Name": "Radhika"},
			{"Last_Name": "Christopher"}
		]
	}
).pretty()
{
	"_id" : ObjectId("5dd631f270fb13eec3963bef"),
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "Fathima_Sheik.123@gmail.com",
	"phone" : "9000054321"
}

NOT in MongoDB

Syntax

要基于 NOT 条件查询文档,您需要使用 $not 关键字,以下是 NOT 的基本语法 −

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

Example

以下示例将检索年龄不大于 25 的文档

> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
	"_id" : ObjectId("5dd6636870fb13eec3963bf7"),
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "Fathima_Sheik.123@gmail.com",
	"phone" : "9000054321"
}