2016-08-22 97 views
0

這是我收集的樣子如何刪除舊數據並在MongoDB中保存新數據?

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

當我保存下一個數據,這

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

我要推'_id':'4'的收集和流行'_id':'1';同樣,當我將'_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

您可以使用capped collection來實現此目的。在mongo殼的一個例子:

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

將創建一個名爲capped加蓋收集,用的100000個字節的最大尺寸,並且將包含最多3個文件的。插入新文檔時,最舊的文檔將被刪除。

> 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: 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: 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