MONGODB

MongoDB 배열 연산자

 MongoDB 배열 연산자

샘플 데이터
db.food.insertOne({_id:1, fruit: ["apple", "banana", "peach"]});
db.food.insertOne({_id:2, fruit: ["apple", "kumquat", "orange"]});
db.food.insertOne({_id:3, fruit: ["cherry", "banana", "apple"]});
db.food.insertOne({_id:4, fruit: ["cherry", "raspberry", "peach"]});

insertOne() = save()

터미널 보기

터미널

 

조건이 모두 일치하는 데이터를 찾는다.
$all(=and)
db.food.find({fruit: {$all : ["apple", "banana"]}});

터미널 보기

터미널

 

조건 중 하나라도 일치하는 데이터를 찾는다.
$in(=or)
db.food.find({fruit: {$in : ["apple", "banana"]}});

터미널 보기

터미널

 

크기가 일치하는 데이터를 찾는다.
$size
db.food.find({fruit: {$size:3}});

터미널 보기

터미널

 

배열에 값을 추가한다.
$push
db.food.updateOne({_id:4}, {$push: {fruit: "strawberry"}});

터미널 보기

터미널

 

배열에 값을 제거한다.
$pull
db.food.updateOne({_id:2}, {$pull : {fruit:"apple"}});

터미널 보기

터미널

 

샘플 데이터
db.post.insertOne({_id:1, replys : [
    {id:1, content:"내용1", userId: 1},
    {id:2, content:"내용2", userId: 1},
    {id:3, content:"내용3", userId: 2},
]});
db.post.insertOne({_id:2, replys : [
    {id:4, content:"내용4", userId: 1},
    {id:5, content:"내용5", userId: 1},
    {id:6, content:"내용6", userId: 2},
]});

 

조건의 결과가 속해 있는 도큐먼트를 찾는다.
“필드명[도큐먼트].필드명”:값
db.post.find({"replys.id":1}).pretty();

 

특정 인덱스가 속해 있는 도큐먼트를 찾는다.
“필드명[도큐먼트].인덱스값.필드명”:값
db.post.find({"replys.0.id":1,"replys.0.userId":1}).pretty();

몽고디비는 인덱스 값을 대괄호([]) 안에 넣지 않는다.

 

쌍따옴표(“”) 잘못 넣었을 때 오류

uncaught exception: SyntaxError: missing : after property id :

 

배열 안에 값을 도큐먼트 단위로 찾는다.
$elemMatch
db.post.findOne({replys:{$elemMatch:{id:1,userId:1}}});

 

위치 연산자
$
db.post.findOne({replys:{$elemMatch:{id:1,userId:1}}},{"replys.$":true});

첫번째 매개변수에서 찾은 배열의 위치를 반환한다내가 적은 위치는 안 먹히기 때문에 위치 연산자로 찾는다.

 

_id 값 비표시
db.post.findOne({replys: {$elemMatch:{id:1, userId:1}}}, {"_id":false, "replys.$":true});

0=false, 1=ture로 대체할 수 있다.

최신글