본문 바로가기
Node.js

MongoDb

by 오늘만 사는 여자 2021. 9. 20.
728x90
반응형

Ref : https://lowell-dev.tistory.com/36

 

[node js] mongoDB 연결하기

1. mongoDB 계정생성 및 로그인 2. mongoDB 클러스터 생성( Create a new cluster ) - 무료티어가 있는 나라 중 가장 가까운 나라 싱가포르로 선택(서울은 무료제공이 없음) - 클러스터를 몇번 이상 생성하면

lowell-dev.tistory.com

 

mongoDb 설치

npm install mongodb

 

NoSQL - MongoDB 예제

//@ts-check

const { MongoClient } = require('mongodb')
const uri =
  'mongodb+srv://아디:비밀번호@cluster0.k3jz5.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const client = new MongoClient(uri, {
  // @ts-ignore
  useNewUrlParser: true,
  useUnifiedTopology: true,
})

async function main() {
  await client.connect()
  const users = client.db('fc21').collection('users')
  const cities = client.db('fc21').collection('cities')

  //Reset
  await users.deleteMany({})
  await cities.deleteMany({})

  await cities.insertMany([
    { name: '서울', population: 1000 },
    { name: '부산', population: 350 },
  ])
  await users.insertMany([
    {
      name: 'Foo',
      birthYear: 2000,
      contacts: [
        {
          type: 'phone',
          number: '+812102456',
        },
        {
          type: 'home',
          number: '+812102456',
        },
      ],
      city: '서울',
    },
    {
      name: 'Bar',
      birthYear: 1995,
      contacts: [
        {
          type: 'phone',
          number: '+812102456',
        },
        {
          type: 'home',
          number: '+812102456',
        },
      ],
      city: '부산',
    },
    {
      name: 'Baz',
      birthYear: 1990,
      city: '서울',
    },
  ])

  //delete
  /*await users.deleteOne({
    name: 'Baz',
  }) */
  //update
  /*users.updateOne(
    {
      name: 'Baz',
    },
    {
      $set: {
        name: 'Boo',
      },
    }
  )*/

  //하나의 변수로 찾기
  /*const cursor = users.find(
    {
      birthYear: {
        //gte : 1990년 이상
        $gte: 1990,
      },
    },
    {
      sort: {
        //-1의 의미는 내림차순
        birthYear: 1,
      },
    }
  ) */

  //contacts에 type이 phone인거 찾기
  /*const cursor = users.find({
    'contacts.type': 'phone',
  })*/

  const cursor = users.aggregate([
    {
      $lookup: {
        from: 'cities',
        localField: 'city',
        foreignField: 'name',
        as: 'city_info',
      },
    },
    {
      $match: {
        //$and, $or
        $and: [
          {
            'city_info.population': {
              $gte: 500,
            },
          },
          {
            birthYear: {
              $gte: 1995,
            },
          },
        ],
      },
    },
    {
      $count: 'num_users',
    },
  ])
  cursor.forEach(console.log)
  // await client.close()
}

main()
728x90
반응형

'Node.js' 카테고리의 다른 글

웹소켓을 통한 실시간 인터랙션 구현  (0) 2021.09.26
NoSQL  (0) 2021.09.20
NoSQL  (0) 2021.09.20
Express  (0) 2021.09.15
리팩토링 프로젝트  (0) 2021.09.15

댓글