스터디노트/DB
-
MongoDB findOne() without _id & MongoDB에서 find와 aggregate 성능 차이스터디노트/DB 2023. 1. 26. 09:39
findOne()으로 조회 시 _id 제외하기 const collection = 'yourCollection'; const result = await collection.findOne( { 조건, }, { projection: { _id: 0 } } ); find와 aggregate 성능차이 Sharding 되지 않은 MongoDB 서버에서는 find와 aggregate 성능 차이가 없다고 한다. find 쿼리나 복잡한 aggregate 쿼리 모두 단일 Shard에서 실행되고 결과를 클라이언트에 전송한다. 참고자료 findOne() without _id : https://stackoverflow.com/questions/48294613/mongo-find-function-wont-exclu..
-
Mongodb add key-value pair to object스터디노트/DB 2022. 11. 8. 10:34
타입이 Object인 도큐먼트에 key-value 쌍인 데이터를 업데이트 하기 const updatedUser = await db.collection('users').updateOne( { name: '태호', }, { $set: { [`personalInfo.${age}${gender}`]: personalInfo, // template literal을 []로 감싸서 작성 }, }, { upsert: true, } );참고자료 https://stackoverflow.com/questions/38887155/how-to-add-key-value-pair-to-object-in-mongodb
-
MongoDB Query for documents array size is greater than스터디노트/DB 2022. 9. 20. 15:16
컬럼.length = 숫자 쿼리 db.collectionName.find({ 컬럼 : { $size : 숫자 } }) 컬럼.length >= 숫자 쿼리 해당 컬럼이 숫자 이상의 사이즈를 갖는 데이터 출력 db.collectionName.find({ '컬럼.숫자' : { $exists : true } }) 참고자료 https://www.thecodebuzz.com/mongodb-query-for-documents-array-size-is-greater-than-mongoshell-cli-node-js/
-
필드가 배열인 경우 MongoDB update하기스터디노트/DB 2022. 7. 26. 12:44
Field가 array인 경우 items : Array $를 사용하여 인덱스별로 적용 컬렉션이름.updateMany( { 'items.name' : 'something' }, { $set : { 'items.$.price' : 1000 } } ); 참고자료 https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/ https://www.mongodb.com/docs/manual/tutorial/query-arrays/
-
MongoDB 사칙연산 쿼리스터디노트/DB 2022. 7. 4. 17:44
$inc $inc를 사용해서 updateData 만큼 더하거나 뺀 값으로 지정할 수 있다. field : -updateData or field : updateData const data = await DB.findOneAndUpdate( { id: requestId }, { $inc: { field: -updateData, 'field.field': -updateData } }, { useFindAndModify: false, } ); $mul 데이터 만큼 곱해서 저장 const data = await DB.findOneAndUpdate( {id: requestId}, {$mul: {field : 숫자}}, { useFindAndModify: false, } ) 참고자료 https://www.zeroch..
-
MongoDB 필드를 참조하여 업데이트 하기스터디노트/DB 2022. 6. 16. 14:30
필드에 참조하여 Update 해야하는 경우 NoSQL 특성상 내부 필드에 참조하여 Update가 불가능하다. forEach문을 사용하여 필드에 접근 forEach를 사용하여 모든 데이터에 접근한다.db.getCollection("컬렉션 명") .find({ 필드명: { $exists: true } }) .forEach(function (elem) { db.getCollection("컬렉션 명").update( { _id: elem._id, }, { $set: { 업데이트하는 필드: elem.참조할 필드 }, } ); }); 참고자료 http://time2relax.net/wp/?p=972
-
MongoDB Aggregation스터디노트/DB 2022. 5. 10. 14:54
$arrayElemAt 배열의 특정 인덱스에 있는 값을 리턴한다. yourField의 0번째 인덱스의 값을 리턴 { $arrayElemAt: ['$yourCollection.yourField', 0] } $ifNull 배열의 특정 인덱스에 있는 값을 리턴한다. yourField의 0번째 인덱스의 값이 null인 경우 ' '을 리턴 { $ifNull: [{ $arrayElemAt: ['$yourCollection.yourField', 0] }, ' '] } 참고자료 MongoDB Aggregation : https://www.mongodb.com/docs/manual/reference/operator/aggregation/