2016-08-22 101 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