MONGODB(Node.js) collection api (CRUD)

Joseph·2024년 1월 15일

해당 collection의 document를 모두 조회Find All Documents

Add a query that returns all the documents.

const findResult = await collection.find({}).toArray();
console.log('Found documents =>', findResult);

해당 collection의 document를 필터링해서 조회 Find Documents with a Query Filter

값이 3인 document만 찾아서 조회
Add a query filter to find only documents which meet the query criteria.

const filteredDocs = await collection.find({ a: 3 }).toArray();
console.log('Found documents filtered by { a: 3 } =>', filteredDocs);

해당 collection의 하나의 document 조회

const getResult = await collection.findOne({ a: 3 }).toArray();
console.log('Found document by { a: 3 } =>', getResult);

해당 collection에 document를 추가 Insert a Document

{ a: 1 }, { a: 2 }, { a: 3 } document를 추가
Add to app.js the following function which uses the insertMany method to add three documents to the documents collection.

const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);

The insertMany command returns an object with information about the insert operations.

해당 collection의 document 업데이트 Update a document

값이 3인 document를 업데이트
The following operation updates a document in the documents collection.

const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });
console.log('Updated documents =>', updateResult);

The method updates the first document where the field a is equal to 3 by adding a new field b to the document set to 1. updateResult contains information about whether there was a matching document to update or not.

해당 collection의 document를 제거 Remove a document

값이 3인 document를 제거
Remove the document where the field a is equal to 3.

const deleteResult = await collection.deleteMany({ a: 3 });
console.log('Deleted documents =>', deleteResult);

참조 사이트 : https://mongodb.github.io/node-mongodb-native/6.3/classes/Collection.html

profile
안녕하세요 프론트와 백 둘다 관심있는 웹개발자 이창무입니다.

0개의 댓글