>  기사  >  데이터 베이스  >  MongoDB의 일반적인 쿼리 작업 소개(코드 포함)

MongoDB의 일반적인 쿼리 작업 소개(코드 포함)

不言
不言앞으로
2019-03-23 16:39:593559검색

이 기사는 MongoDB의 일반적인 쿼리 작업(코드 포함)을 소개합니다. 필요한 친구가 참고할 수 있기를 바랍니다.

머리말: 사용된 시각화 도구는 공식 웹사이트인 Studio 3T입니다-->https://studio3t.com/
버전 번호: MongoDB 쉘 버전 v3.4.2
사용 방법: https://blog.csdn.net /weixin_ ...
주의사항: 연산자에 집중하세요.
검색방법 : 이 페이지에서 ctrl+F를 누르고 키워드 검색을 입력하세요

1. 자주 사용하는 Query
작업의 편의를 위해 원본 데이터를 삽입하기 전 문서를 모두 삭제해주세요. (프로젝트에서는 주의해서 작업해주세요! ):

db.getCollection("inventory").deleteMany({})

0. 모든 문서 보기

db.getCollection("inventory").find({})

1. 개체 검색
1.1. 원본 데이터

db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

1.2. size.w가 21인 문서를 찾습니다. , size.uom은 cm

db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

1.3과 같습니다. size.uom이 in

db.inventory.find( { "size.uom": "in" } )

과 동일한 문서를 찾으세요. 참고: 단일 객체 속성을 찾을 때 따옴표를 추가하세요!

1.4.객체에서 지정된 필드를 찾아 반환합니다

db.inventory.find(
   { status: "A" },
   { item: 1, status: 1, "size.uom": 1 }
)

2. 원본 데이터

db.inventory.find(
   { status: "A" },
   { "size.uom": 0 }
)
2.2. ["red", "blank"] 문서
db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

참고: 포함 관계가 아닙니다. 즉, 태그: ["red", "blank", "plain"]은 포함되지 않습니다

2.3. 빨간색 문서

db.inventory.find( { tags: ["red", "blank"] } )

를 포함하는 태그 참고: db.inventory.find( { 태그: ["red"] } )를 이와 같이 작성할 수 없습니다. 이는 태그가 빨간색

3인 문서를 찾고 있음을 의미합니다. 배열에 포함된 개체 검색

3.1.원본 데이터

db.inventory.find( { tags: "red" } )
3.2.배열에서 조건에 맞는 개체(포함되지 않음)를 찾습니다. 배열이 반환됩니다.
db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

필드 순서를 엄격히 따르세요. 교체하는 경우 필드 순서는 다음과 같습니다.

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

3.3. qty=5, 또는 객체(또는 다른 요소 객체) Warehouse=A

db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
找 不 到3.4.에서 객체 배열을 찾아 객체의 특정 속성을 반환합니다

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

4.1.

4.2. 지정된 필드를 쿼리하고 반환합니다.

상태=A인 조건에서 _id, 항목, 상태 필드를 반환합니다.

db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )

결과:

db.inventory.insertMany( [
  { item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
  { item: "notebook", status: "A",  size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
  { item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
  { item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
  { item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
4.3에서는 _id가 자동으로 전달되고 제거될 수 있음을 알고 있습니다. 다음과 같습니다

id가 없는 쿼리:


db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

참고: id를 제외하고 필터링할 수 있습니다. 동시에 다른 필드는 0이면서 1

을 입력할 수 없습니다. 예:

{ "_id" : ObjectId("5c91cd53e98d5972748780e1"), 
    "item" : "journal", 
    "status" : "A"}
// ----------------------------------------------
{ "_id" : ObjectId("5c91cd53e98d5972748780e2"), 
    "item" : "notebook", 
    "status" : "A"}
// ----------------------------------------------
{ "_id" : ObjectId("5c91cd53e98d5972748780e5"), 
    "item" : "postcard", 
    "status" : "A"}
는 오류


4.4. 특정 필드를 제외하고 다른 필드를 반환합니다

db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
5. null 또는 존재하지 않는 키 찾기

5.1. item이 null인 문서 또는 itemMongoDB의 일반적인 쿼리 작업 소개(코드 포함)

db.inventory.find( { status: "A" }, { item: 1, status: 0 } )

2. Operator

1. $lt less than
1.1, 원본 데이터

db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )

1.2를 포함하지 않는 문서를 찾습니다. .h"는 15보다 작습니다

db.inventory.insertMany([
   { _id: 1, item: null },
   { _id: 2 }
])

1.3, $lt는 AND 와 함께 사용되어 15보다 작은 size.h를 찾고 size.uom은 포함되어 있으며 상태는 D

db.inventory.find( { item: null } )

2, $lte의 문서입니다. 같음
2.1, 원본 데이터
db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

2.2, 20보다 작거나 같은 문서 instock.qty를 찾습니다. 배열에 조건을 충족하는 개체가 있는 한 전체 배열

db.inventory.find( { "size.h": { $lt: 15 } } )


3, $gt가

3.1보다 큼, 원본 데이터

db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
3.2, 25

db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

보다 큰 dark_cm이 있는 문서를 찾으세요. 참고: 배열에 25보다 큰 요소가 포함되어 있는 한 적격입니다

3.3. 희미한 값이 15보다 크거나 20보다 작거나 둘 다 15보다 크고 20

db.inventory.find( { 'instock.qty': { $lte: 20 } } )

3.4입니다. 희미한 값이 22보다 크고 30보다 작은 문서를 찾습니다(배열의 요소가 더 큰지 확인하려면 22개 미만, 30개 미만, 배열의 모든 요소를 ​​판단하는 대신)
db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

3.5. 배열 위치를 기준으로 검색

dim_cm의

두 번째 요소가 25

db.inventory.find( { dim_cm: { $gt: 25 } } )

4보다 큰 문서를 찾습니다. 배열 길이에서

태그가

length가 3


db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
5인 문서를 찾습니다. $gte는

5.1보다 크거나 같습니다. 원본 데이터는

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
5.2입니다. 첫 번째의 수량이 있는 문서 컬렉션을 찾습니다. 배열의 요소(객체)가 20보다 크거나 같습니다.

db.inventory.find( { "dim_cm.1": { $gt: 25 } } )
6. $elemMatch 객체의 속성 일치

6.1 배열에서 qty=5, Warehouse="A"와 일치하는 객체를 찾아 문서를 반환합니다. collection

db.inventory.find( { "tags": { $size: 3 } } )
6.2 10보다 큰 수량

문서 모음

과 20보다 작거나 같은 개체를 배열에서 찾습니다.

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

如果不使用 $elemMatch 的话,就表示 qty 大于 10 或者小于等于 20,官方文档意思是,不在数组的某一个元素找 既满足条件 A 又满足条件 B 的 qty,而是在数组的所有元素上找,满足条件 A 或满足条件 B 的 qty

db.inventory.find( { "instock.qty": { $gt: 10,  $lte: 20 } } )

7、$slice 返回数组特定位置的元素
7.1、原数据

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

7.2、查找并返回 tags 数组的最后一个元素

db.inventory.find( { item: "journal" }, { item: 1, qty: 0, tags: { $slice: -1 } } )

结果:

{ 
    "_id" : ObjectId("5c91dce5e98d5972748780e6"), 
    "item" : "journal", 
    "tags" : [
        "red"
    ]
}

8、$type 返回指定类型的元素
8.1、原数据

db.inventory.insertMany([
   { _id: 1, item: null },
   { _id: 2 }
])

8.2、返回 null 类型的数据

db.inventory.find( { item : { $type: 10 } } )

类型如下:

MongoDB의 일반적인 쿼리 작업 소개(코드 포함)

详细文档请看:https://docs.mongodb.com/manu...

9、$exists 返回存在/不存在的键
查找不存在 item 键的数据

db.inventory.find( { item : { $exists: false } } )

10、$all 包含
10.1、原数据

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

10.2、查找 tags 数组包含 ["red", "blank"] 的文档

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

综上:
数组用的:$all$size$slice
对象用的:$elemMatch

Query查询的详细文档请看:https://docs.mongodb.com/manu...
Operator的详细文档请看:https://docs.mongodb.com/manu...

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的mongodb视频教程栏目!

위 내용은 MongoDB의 일반적인 쿼리 작업 소개(코드 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제