[Mongo DB] Find
Find
find 와 findOne의 차이?
find는 많은 데이터, 데이터가 줄줄이 보여짐
findOne은 하나의 데이터, 데이터가 구조적으로 보여짐
Find를 하기 위해서 일단 데이터를 insert 한다.
function insertMassivePost() {
for(var i = 0; i < 20000; i++){
var post = {
"id" : ( i + 1 ),
"subject" : "Hello" + ( i + 1 ),
"content" : "MongoDB" + ( i + 1 ),
"author" : "smahn",
"pageView" : 0
}
db.post.insert(post);
}
}
그리고 로보몽고에서 확인해보면, 아래와 같이 데이터가 잘 들어간 것을 확인할 수 있다.
조건을 지정하여 find를 해본다.
id 가 30인 것을 찾아라.
db.post.find({"id":30});
id 가 30보다 작은것을 찾아라.
db.post.find({"id":{"$lt":30}});
id 가 15보다 크고 30보다 작은것을 찾아라.
db.post.find({"id":{"$gt":15, "$lt":30}});
Id가 1, 3, 5, 7, 9 인것을 찾아라.
db.post.find({"id" : { "$in" : [1, 3, 5, 7, 9] }});
Id가 1, 3, 5, 7, 9가 아닌 것을 찾아라.
db.post.find({"id" : { "$nin" : [1, 3, 5, 7, 9] }});
id 가 15 이거나 "subject" 가 "Hello19988" 인것을 찾아라.
db.post.find({ "$or" : [{"id":15}, {"subject":"Hello19988"}] })
Id가 짝수인 모든 것을 찾아라.
db.post.find( { "id" : { "$mod" : [2,0] } } );
Blog 컬렉션에 데이터 넣고, tags에 mongo가 있는 것을 찾기
데이터 넣기
use blog
var post = {
"subject" : "MongoDB Test",
"description" : "Hello",
"author" : "smahn",
"tags" : [
"java", "mongoDB", "mongo", "Mongo", "bigData"
],
"replies" : [
{
"author" : "mcjang",
"description" : "^^"
},
{
"author" : "jhnam",
"description" : "-_-"
}
]
}
db.post.insert(post);
tags에 mongo가 있는 것을 찾기
db.post.find({ "tags" : "mongo" });
Tags에 java와 mongo가 있는 것을 찾아라.
db.post.find({ "tags": {
"$all" : ["java","mongo"]
}
});
Author가 jhnam이고 description이 -_- 인 댓글의 게시글을 찾아라.
db.post.find({"replies":{"author":"jhnam", "description":"-_-"} })
jhnam이 댓글을 쓴 게시글을 찾아라.
배열요소가 있으면 $eleMatch를 쓴다.
db.post.find({"replies":{
"$elemMatch" : {
"author":"jhnam"
}
}
})