다음을 통해 공유


JavaScript를 사용하여 Azure Cosmos DB for MongoDB에서 문서 관리

적용 대상: MongoDB

문서를 삽입, 업데이트 및 삭제하는 기능을 사용하여 MongoDB 문서를 관리합니다.

참고 항목

예제 코드 조각은 GitHub에서 JavaScript 프로젝트로 사용할 수 있습니다.

API for MongoDB 참조 설명서 | MongoDB 패키지(npm)

문서 삽입

JSON 스키마로 정의된 문서를 컬렉션에 삽입합니다.

// get database client for database
// if database or collection doesn't exist, it is created
// when the doc is inserted

// insert doc
const doc = { name: `product-${random}` };
const insertOneResult = await client
  .db('adventureworks')
  .collection('products')
  .insertOne(doc);
console.log(`Insert 1 - ${JSON.stringify(insertOneResult)}`);

// insert docs
const docs = [{ name: `product-${random}` }, { name: `product-${random}` }];
const insertManyResult = await client
  .db('adventureworks')
  .collection('products')
  .insertMany(docs);
console.log(`Insert many ${JSON.stringify(insertManyResult)}`);

위의 코드 조각은 다음 예제 콘솔 출력을 표시합니다.

Insert 1 - {"acknowledged":true,"insertedId":"62b2394be4042705f00fd790"}
Insert many {"acknowledged":true,"insertedCount":2,"insertedIds":{"0":"62b2394be4042705f00fd791","1":"62b2394be4042705f00fd792"}}
done

문서 ID

문서에 대한 ID(_id)를 제공하지 않으면 BSON 개체로 만들어집니다. 제공된 ID의 값은 ObjectId 메서드를 사용하여 액세스됩니다.

ID를 사용하여 문서를 쿼리합니다.

const query = { _id: ObjectId("62b1f43a9446918500c875c5")};

문서 업데이트

문서를 업데이트하려면 업데이트해야 하는 문서의 속성 세트와 함께 문서를 찾는 데 사용되는 쿼리를 지정합니다. 문서가 아직 없는 경우 삽입하는 문서를 업서트하도록 선택할 수 있습니다.

const product = {
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 3',
  quantity: 15,
  sale: true,
};

const query = { name: product.name };
const update = { $set: product };
const options = { upsert: true, new: true };

const upsertResult = await client
  .db('adventureworks')
  .collection('products')
  .updateOne(query, update, options);

console.log(
  `Upsert result:\t\n${Object.keys(upsertResult).map(key => `\t${key}: ${upsertResult[key]}\n`)}`
);

위의 코드 조각은 삽입에 대한 다음 예제 콘솔 출력을 표시합니다.

Upsert result:
        acknowledged: true
,       modifiedCount: 0
,       upsertedId: 62b1f492ff69395b30a03169
,       upsertedCount: 1
,       matchedCount: 0

done

위의 코드 조각은 업데이트에 대한 다음 예제 콘솔 출력을 표시합니다.

Upsert result:
        acknowledged: true
,       modifiedCount: 1
,       upsertedId: null
,       upsertedCount: 0
,       matchedCount: 1

done

컬렉션에 대한 대량 업데이트

bulkWrite 작업을 사용하여 한 번에 여러 작업을 수행할 수 있습니다. Azure Cosmos DB에 대한 대량 쓰기를 최적화하는 방법에 대해 자세히 알아봅니다.

다음과 같은 대량 작업을 사용할 수 있습니다.

const doc1 = {
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 3',
  quantity: 15,
  sale: true,
};
const doc2 = {
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 7',
  quantity: 5,
  sale: true,
};

// update docs with new property/value
const addNewProperty = {
  filter: { category: 'gear-surf-surfboards' },
  update: { $set: { discontinued: true } },
  upsert: true,
};

// bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany
const upsertResult = await client
  .db('adventureworks')
  .collection('products')
  .bulkWrite([
    { insertOne: { document: doc1 } },
    { insertOne: { document: doc2 } },
    { updateMany: addNewProperty },
  ]);

console.log(`${JSON.stringify(upsertResult)}`);

위의 코드 조각은 다음 예제 콘솔 출력을 표시합니다.

{
  "ok":1,
  "writeErrors":[],
  "writeConcernErrors":[],
  "insertedIds":[
    {"index":0,"_id":"62b23a371a09ed6441e5ee30"},
    {"index":1,"_id":"62b23a371a09ed6441e5ee31"}],
  "nInserted":2,
  "nUpserted":0,
  "nMatched":10,
  "nModified":10,
  "nRemoved":0,
  "upserted":[]
}
done

문서 삭제

문서를 삭제하려면 쿼리를 사용하여 문서를 찾은 방법을 정의합니다.

const product = {
  _id: new ObjectId('62b1f43a9446918500c875c5'),
  category: 'gear-surf-surfboards',
  name: 'Yamba Surfboard 3',
  quantity: 15,
  sale: true,
};

const query = { name: product.name };

// delete 1 with query for unique document
const delete1Result = await client
  .db('adventureworks')
  .collection('products')
  .deleteOne(query);
console.log(
  `Delete 1 result:\t\n${Object.keys(delete1Result).map(key => `\t${key}: ${delete1Result[key]}\n`)}`
);

// delete all with empty query {}
const deleteAllResult = await client
  .db('adventureworks')
  .collection('products')
  .deleteMany({});
console.log(
  `Delete all result:\t\n${Object.keys(deleteAllResult).map(key => `\t${key}: ${deleteAllResult[key]}\n`)}`
);

위의 코드 조각은 다음 예제 콘솔 출력을 표시합니다.

Delete 1 result:
        acknowledged: true
,       deletedCount: 1

Delete all result:
        acknowledged: true
,       deletedCount: 27

done

참고 항목