mongoDB operators - Expressive, Array Query Operators, Projection, Dot notation

ToastEggsToast·2021년 2월 20일
0

mongoDB

목록 보기
2/7

$

$ -> field의 값에 접근하기 위한 용도로서 사용할 수 있음.
$expr-> expressive Query operator. 같은 document 내부의 서로 다른 field값을 비교할 수 있음.

db.trips.find({
	"$expr": {
    	"$eq": [ "$start station id", "$end satation id" ]
    }
})

start station id 필드의 값과 end station id 필드의 값이 같은 도큐먼트를 찾을 때.

db.trips.find({
	"$expr": {
    	"$and": [
        	{"$gt": ["$trip duration", 1200]},
        	{"$eq": ["$start station id", "$end station id"]}
        ]
    }
})

trip duration 필드의 값이 1200보다 크고, start station id 필드의 값과 end station id 필드의 값이 같은 도큐먼트를 찾을 때.

Array operators

db.air_bnb.find({ amenities: "shampoo" }) => 샴푸가 들어간 amenities를 가진 document 반환

db.air_bnb.find({ amenities: ["shampoo"] }) => amenities: ["shampoo"] 인 document 반환

array를 값으로 가지는 field에서는 array element의 순서도 document를 찾는데에 영향을 준다.
순서에 영향을 받지 않게 하려면 $all 이라는 operator를 사용해야함.

db.air_bnb.find({ amenities: { "$all": ["shampoo"] } }) => amenities array에 shampoo가 포함된 모든 document 반환

db.air_bnb.find({ amenities: { "$size": 20, "$all": ["shampoo"] } }) => amenities array에 shampoo가 포함된 모든 document들 중 amenities의 갯수가 20개인 document만 반환

$elemMatch

array 의 element에 접근하기 위함.

"$elemMatch": { <field>: <value> }

db.grades.find({ "class_id": 431 },
               { "scores": { "$elemMatch": { "score": { "$gt": 85 } } }
             }).pretty()

projection

projection -> Specifies which fields should or should not be included in the result cursor.
결과로 리턴되는 docuement에서 보여질, 혹은 보이지 않을 field를 정렬. 0 -> 보이지 않음, 1 -> 보임. 0과 1을 함께 쓸 수 없다. 단 _id의 경우에는 0 혼용이 가능하다.

dotNotation [.]

document field의 subfield로 접근하는 방법, 혹은 array 형태의 field의 n 번째에 접근하는 방법

profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글