MongoDB-쿼리 문서

이 장에서는 MongoDB 컬렉션에서 문서를 쿼리하는 방법을 배웁니다.

find () 메서드

MongoDB 컬렉션에서 데이터를 쿼리하려면 MongoDB의 find() 방법.

통사론

기본 구문 find() 방법은 다음과 같습니다-

>db.COLLECTION_NAME.find()

find() 메소드는 모든 문서를 구조화되지 않은 방식으로 표시합니다.

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 } ] }
>

pretty () 메서드

형식화 된 방식으로 결과를 표시하려면 pretty () 메서드를 사용할 수 있습니다.

통사론

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

다음 예제는 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
		}
	]
}

findOne () 메서드

find () 메소드 외에도 findOne() 하나의 문서 만 반환하는 메서드입니다.

통사론

>db.COLLECTIONNAME.findOne()

다음 예제는 제목이 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
}

MongoDB에서 조항이 동일한 RDBMS

일부 조건을 기준으로 문서를 조회하려면 다음 작업을 사용할 수 있습니다.

조작 통사론 RDBMS 상당
평등 {<키> : {$ eg; <값>}} db.mycol.find ({ "by": "튜토리얼 포인트"}). pretty () 여기서 = '튜토리얼 포인트'
보다 작음 {<키> : {$ lt : <값>}} db.mycol.find ({ "likes": {$ lt : 50}}). pretty () 좋아요 <50
보다 작음 {<키> : {$ lte : <값>}} db.mycol.find ({ "likes": {$ lte : 50}}). pretty () 좋아요 <= 50
보다 큰 {<키> : {$ gt : <값>}} db.mycol.find ({ "likes": {$ gt : 50}}). pretty () 좋아요> 50 개
같음보다 큼 {<키> : {$ gte : <값>}} db.mycol.find ({ "likes": {$ gte : 50}}). pretty () 좋아요> = 50
같지 않음 {<키> : {$ ne : <값>}} db.mycol.find ({ "likes": {$ ne : 50}}). pretty () 좋아요! = 50
배열의 값 {<키> : {$ in : [<값 1>, <값 2>, …… <값 N>]}} db.mycol.find ({ "name": {$ in : [ "Raj", "Ram", "Raghu"]}}). pretty () 이름이 : [ "Raj", "Ram", "Raghu"]의 값과 일치하는 경우
배열에없는 값 {<키> : {$ nin : <값>}} db.mycol.find ({ "name": {$ nin : [ "Ramu", "Raghav"]}}). pretty () 이름 값이 배열에없는 경우 : [ "Ramu", "Raghav"] 또는 전혀 존재하지 않음

그리고 MongoDB에서

통사론

AND 조건을 기반으로 문서를 쿼리하려면 $ and 키워드를 사용해야합니다. 다음은 AND의 기본 구문입니다.

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

다음 예제는 'tutorials point'가 작성하고 제목이 'MongoDB Overview'인 모든 튜토리얼을 보여줍니다.

> 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 절에서 원하는 수의 키, 값 쌍을 전달할 수 있습니다.

또는 MongoDB에서

통사론

OR 조건을 기반으로 문서를 쿼리하려면 다음을 사용해야합니다. $or예어. 다음은 기본 구문입니다.OR

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

다음 예제는 'tutorials point'로 작성되었거나 제목이 'MongoDB Overview'인 모든 튜토리얼을 보여줍니다.

>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"
}
>

AND 및 OR 함께 사용

다음 예제는 좋아요가 10 개 이상이고 제목이 'MongoDB Overview'이거나 by가 'tutorials point'인 문서를 보여줍니다. 절이있는 동등한 SQL'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"
}
>

MongoDB의 NOR

통사론

NOT 조건을 기반으로 문서를 쿼리하려면 $ not 키워드를 사용해야합니다. 다음은 기본 구문입니다.NOT

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

컬렉션에 3 개의 문서를 삽입했다고 가정합니다. empDetails 아래와 같이-

db.empDetails.insertMany(
	[
		{
			First_Name: "Radhika",
			Last_Name: "Sharma",
			Age: "26",
			e_mail: "[email protected]",
			phone: "9000012345"
		},
		{
			First_Name: "Rachel",
			Last_Name: "Christopher",
			Age: "27",
			e_mail: "[email protected]",
			phone: "9000054321"
		},
		{
			First_Name: "Fathima",
			Last_Name: "Sheik",
			Age: "24",
			e_mail: "[email protected]",
			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" : "[email protected]",
	"phone" : "9000054321"
}

MongoDB가 아닙니다.

통사론

NOT 조건을 기반으로 문서를 쿼리하려면 $ not 키워드를 사용해야합니다. 다음은 기본 구문입니다. NOT

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

다음 예는 나이가 25 세 이하인 문서를 검색합니다.

> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
	"_id" : ObjectId("5dd6636870fb13eec3963bf7"),
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "[email protected]",
	"phone" : "9000054321"
}