본문 바로가기
Database/NoSQL

[MongoDB] 실전 쿼리 작성

by lumination 2025. 6. 16.

데이터 샘플

{
  "_id": {
    "$oid": "573a1399f29313caabcee864"
  },
  "plot": "A serial adventure writer with problems in his personal life lives out the adventures of his literary hero, King of Adventurers.",
  "genres": [
    "Action",
    "Adventure"
  ],
  "runtime": 91,
  "cast": [
    "Jet Li",
    "Rosamund Kwan",
    "Charlie Yeung",
    "Takeshi Kaneshiro"
  ],
  "num_mflix_comments": 0,
  "poster": "https://m.media-amazon.com/images/M/MV5BNjNmMGQzZDktMTFmZC00MGNkLTg1OWItNWRmOThmNDEwNTlmXkEyXkFqcGdeQXVyNjk5NzY4OTk@._V1_SY1000_SX677_AL_.jpg",
  "title": "Dr. Wai in the Scriptures with No Words",
  "fullplot": "A serial adventure writer with problems in his personal life lives out the adventures of his literary hero, King of Adventurers.",
  "languages": [
    "Cantonese"
  ],
  "released": {
    "$date": "1996-03-14T00:00:00.000Z"
  },
  "directors": [
    "Siu-Tung Ching"
  ],
  "writers": [
    "Wai-Lun Lam",
    "Sandy Shaw",
    "Cheuk-Hon Szeto"
  ],
  "awards": {
    "wins": 1,
    "nominations": 1,
    "text": "1 win & 1 nomination."
  },
  "lastupdated": "2015-08-28 00:00:15.410000000",
  "year": 1996,
  "imdb": {
    "rating": 5.9,
    "votes": 1423,
    "id": 110463
  },
  "countries": [
    "Hong Kong"
  ],
  "type": "movie",
  "tomatoes": {
    "viewer": {
      "rating": 3.3,
      "numReviews": 2966,
      "meter": 47
    },
    "dvd": {
      "$date": "2004-11-09T00:00:00.000Z"
    },
    "lastUpdated": {
      "$date": "2015-09-14T17:48:21.000Z"
    }
  },
  "plot_embedding": [
    0.017812748,
    -0.017812748,
  ]
}

 

 

쿼리 작성

[
	// year과 type이 둘 다 해당되는 것
	{$match : {year: 1914, type: "movie"}}


	// year 또는 type이 해당되는 것
	{$match :
		{$or: [
			{year : 1914},
			{type : "mov1ie"}]}}


	// genres가 Action인 것
	{$match : {genres: "Action"}}


	// generes가 Action과 Adventure 모두 있는 것
	{$match : {genres: {$all : ["Action", "Adventure"]}}}


	// genres가 Action과 Adventure이면서 genres array의 사이즈가 2인 것
	{$match : {$and: [
		{genres : {$all : ["Action", "Adventure"]}},
		{genres : {$size : 2}}
	]}}
    
 
	// year이 1910보다 크면서, idmb.rating 7.0이거나 award.wins 0보다 큰 것
	{$match: {
		$and : [
			{year : {$gte: 1910}},
				{$or : [
					{"imdb.rating" : {$gte : 7.0}},
 					{"award.wins" : {$gt : 0}}]}]}
	}


	// 같은 문서에서 검색. imdb.rating이 award.wins보다 큰 경우
	{$match: {
		$expr : {$gt: ["imdb.rating","award.wins"] }
	}}

]

 

'Database > NoSQL' 카테고리의 다른 글

[MongoDB] Aggregation Pipeline 동작 방식  (0) 2025.06.17
[MongoDB] 실전 쿼리 작성2  (0) 2025.06.17
[MongoDB] 데이터 파이프라인과 Lookup  (0) 2025.06.16
[MongoDB] Cursor  (0) 2025.06.16
[MongoDB] 정렬과 페이징  (0) 2025.06.16