Mongodb 몽고디비 데이터 조회(find), collection 생성 삽입 query 명령어

Mongodb 데이터 조회(find), collection 생성, document 삽입 query 명령어

Mongodb 사용법에 대해서 알아보겠습니다.

Mongodb 사용 시 빈번하게 사용하는 Collection create, Document insert,

다양하게 활용가능한 find(조회) query(명령어) 에 대해서 살펴봅니다.

Mongodb Collection 생성 및 Document 삽입

wow라는 이름의 collection 생성

db.createCollection("wow")

1개 document insert

db.wow.insertOne({ "korean" : "사이즈", "english":"size" } )

여러개 document insert

db.wow.insertMany(
[ 
{ "korean" : "사이즈", "english" : "size"},
{ "korean" : "코튼", "english" : "cotton"},
{ "korean" : "색상", "english" : "color"}
])

mongodb find 조회

collection 전체 조회

db.wow.find({})

ObjectId로 조회

db.getCollection('wow').find({_id:ObjectId('5bee16ac39ab840015adbec3')})

특정 값 조회

db.getCollection('wow').find({"korean":"사이즈"})

조건 여러개로 조회

db.getCollection('wow').find({"korean":"사이즈","english" : "size" })

특정 조회 값의 특정 필드만 조회

  • english 필드만 노출

  • _id는 0으로 설정하지 않으면 항상 노출됨

db.getCollection('wow').find({"korean":"사이즈"},{_id:0, "english":1})

OR 쿼리

  • korean 이 사이즈이거나, english가 color인 것 조회

    db.getCollection('wow').find({

      $or: [
      {"korean": "사이즈"}, 
      {"english":"color"}
      ]
    })

AND 쿼리

  • korean 이 사이즈이고, english가 size인 것 조회

    db.getCollection('wow').find({

      $and : [
      {"korean":"사이즈"},
      {"english": "size"}
      ]
    })

기간 조회

  • $gte : 이상

  • $lte : 이하

  • $gt : 초과

  • $lt : 미만

  • created_at key는 추가된 상태어야 함

db.getCollection('wow').find({created_at:{$gte:ISODate("2019-08-27T14:00:35.386Z"),$lte:ISODate("2019-08-29T14:00:35.386Z") }})

정규식 활용 조회

  • english 가 s로 시작하지 않는 것 조회
db.products.find({english: { $not: /^s*/ }})
  • code 가 특정글자(code_)로 시작하는 대상 조회
db.getCollection('products').find({"code":{$regex : /code_\w+/}})
db.getCollection('products').find({"code":{$regex : "merge_"}}) 

collection 내림차순 조회

db.getCollection('wow').find({}).sort({_id:-1})

Index 조회

db.getCollection('wow').getIndexes()

key가 존재하는 것 조회

db.getCollection('wow').find({"korean":{$exists:true}})

key 가 존재하는 결과 갯수 조회 

  • mongodb find 개수를 count()로 find 로 조회한 결과의 갯수를 확인 가능
db.getCollection('wow').find({"korean":{$exists:true}}).count()

댓글

Designed by JB FACTORY