2016-08-22 3 views
0

이 내 모음입니다 보이는 내가 컬렉션에 '_id':'4'을 밀어 '_id':'1'를 팝업 할이전 데이터를 제거하고 MongoDB에 새로운 데이터를 저장하는 방법?

'_id' will be '4', 'name':'John', 'message':'howdy'. 

내가 다음에 데이터를 저장

[{ 
    '_id':'1', 
    'name':'John', 
    'message':'Hi' 
}, 
{ 
    '_id':'2', 
    'name':'John', 
    'message':'Hey' 
}, 
{ 
    '_id':'3', 
    'name':'John', 
    'message':'Hello' 
}] 

,

같은; 마찬가지로, 동일한 컬렉션 '_id':'5'을 저장할 때 '_id':'2' 등이 제거됩니다.

이전 데이터를 삭제하고 컬렉션 내의 제한 항목에 대한 새로운 데이터를 저장하고 싶습니다.

MongoDB 스키마에 어떻게 이것을 써야하나요? 당신은 어떤 스키마를 쓸 필요가없는

답변

1

, 당신은 약간의 logic.that을 할 필요가있는 컬렉션을 카운트하여 새 문서의 분할 _id의

카운트 수이고 여기에 나머지를 할당합니다. 이제이 새로운 _id는 문서를 업데이트해야하는 곳입니다.

count = numberOfDocumentsInCollection newDoc._id = newDoc._id%count 

다음은 전체 코드입니다.

var MongoClient = require('mongodb').MongoClient 
var url = 'mongodb://localhost:27017/testdb'; 

var newDoc = { 
    _id:4, 
    name:"John", 
    message:"this is vajahat" 
} 
MongoClient.connect(url,function(err,db){ 
    if(err) 
    return console.log(err); 
    var collection = db.collection('test'); 
    collection.count(function(err,count){ 
    // this is number of documents 
    var idToBeUpdatedAt= newDoc._id%count;//<<-------Here is the trick 
    delete newDoc._id; 
    console.log(idToBeUpdatedAt,count); 
    collection.updateOne({"_id":idToBeUpdatedAt},{"$set":newDoc},function(err,updated){ 
     if(err) 
     return console.log(err); 
     console.log("updated"); 
     db.close(); 
    }); 
    }); 
}) 
1

이러한 목적으로 캡핑 된 컬렉션을 사용할 수 있습니다. mongo 쉘 예 :

db.createCollection('capped', {capped: true, size: 100000, max: 3}) 

는 100000 바이트의 최대 크기 capped라는 덮인 모음을 만들 것이며, 3 개 문서의 최대 포함됩니다. 새 문서를 삽입하면 가장 오래된 문서가 삭제됩니다.

> db.capped.insert({_id: 4, name: 'John', message: 'howdy'}) 

> db.capped.find() 
{ "_id" : 2, "name" : "John", "message" : "Hey" } 
{ "_id" : 3, "name" : "John", "message" : "Hello" } 
{ "_id" : 4, "name" : "John", "message" : "howdy" } 

가장 오래된 문서가 자동으로 컬렉션에서 제거 : 새 문서를 삽입

> db.capped.insert({_id: 1, name: 'John', message: 'Hi'}) 
> db.capped.insert({_id: 2, name: 'John', message: 'Hey'}) 
> db.capped.insert({_id: 3, name: 'John', message: 'Hello'}) 

> db.capped.find() 
{ "_id" : 1, "name" : "John", "message" : "Hi" } 
{ "_id" : 2, "name" : "John", "message" : "Hey" } 
{ "_id" : 3, "name" : "John", "message" : "Hello" } 

. 마찬가지로 :
> db.capped.insert({_id: 5, name: 'John', message: 'hello'}) 

> db.capped.find() 
{ "_id" : 3, "name" : "John", "message" : "Hello" } 
{ "_id" : 4, "name" : "John", "message" : "howdy" } 
{ "_id" : 5, "name" : "John", "message" : "hello" } 

은 자세한 내용은 Capped Collections page를 참조하십시오.

관련 문제