2016-08-22 22 views
0

これは私が古いデータを削除してMongoDBに新しいデータを保存するには?

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

は、私が収集し、ポップ'_id':'1''_id':'4'をプッシュしたい、次のデータを保存すると、

[{ 
    '_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を参照してください。

関連する問題