[英]mongodb - capped collections with nodejs
我正在嘗試使用Node.js(使用本機MongoDB驅動程序)在MongoDB中設置和更新一些上限集合。 我的目標是,在運行app.js時,將文檔插入到上限集合中,並更新上限集合中的現有文檔。 這兩個都在setInterval()
上運行,所以每隔幾秒鍾。
我的問題:
db.createCollection("collectionName", { capped : true, size : 100000, max : 5000 } )
。 這將為我創建上限集合,但每次調用它時都會調用createCollection()
而不是更新或插入 - 如果我調用createCollection()
,一旦集合已經存在,它是否會完全覆蓋現有集合? db.runCommand({"convertToCapped": "collectionName", size: 100000, max : 5000 });
。 這個問題是節點沒有看到runCommand()
作為有效函數而且它出錯。 是否有其他東西我打算要求它讓這個工作? 它適用於mongo cli但不在節點內 db.collections.find()
和一些查詢,但在節點內它聲明find()
不是有效的函數 collection.update()
向現有文檔添加一些新字段? 讓我們說文檔是一些簡單的對象,如{key1: "value", key2: "value"}
但我有一個包含{key3: "value"}
。 當前文檔中不存在鍵3,如何將其添加到當前存在的內容中? 這與上面的#4有些相關,因為我不確定將什么傳遞給查詢參數,因為find()
似乎不能很好地與節點一起使用。 關於有關上限集合並自動創建它們的問題1 - 4,有幾種方法可以做到這一點。 一方面,您可以運行一個腳本來初始化您的數據庫,以便在您第一次運行它時,它可以為您的客戶端提供上限集合。 另一方面,在插入文檔之前,您可以檢查給定集合中是否有任何文檔。 如果有,您只需插入文檔,如果沒有,則創建上限集合,然后將文檔作為回調插入該函數。 它會像這樣工作:
var host = "localhost",
port = 27017,
dbName = "so";
var MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server;
var mongoclient = new MongoClient(new Server(host, port));
var db = mongoclient.db(dbName);
db.open(function(err, db) {
if(err) throw err;
// Capped collection.
var capped = db.collection('capped');
// Document to be inserted.
var document = { "foo": 1, "bar": 1 }
capped.find().count(function(err, count) {
if(err) throw err;
if (count === 0) {
console.log("Creating collection...");
db.createCollection("capped",
{ "capped": true,
"size": 100000,
"max": 5000 },
function(err, collection) {
if(err) throw err;
// Insert a document here.
console.log("Inserting document...");
collection.insert(document, function(err, result) {
if (err) throw err;
});
});
} else {
// Insert your document here without creating collection.
console.log("Inserting document without creating collection...");
capped.insert(document, function(err, result) {
if (err) throw err;
});
}
});
});
關於問題5,您可以使用findOne()
在集合中查找文檔,但這不一定是第一個或最后一個。 如果要保證第一個或最后一個,可以使用sort()
和limit()
運行find()
1.按_id
升序排序應該為您提供第一個文檔。 更多信息在這里 。
// Sort 1 for ascending, -1 for descending.
capped.find().sort([["_id", 1]]).limit(1).nextObject(function(err, item) {
console.log(item);
});
最后,對於問題6,您只需將$set
運算符與update()
方法一起使用即可。 更多信息在這里 。
capped.update({ "foo": 1 }, { "$set": { "bar": 2 } }, {}, function(err, result) {
console.log(result);
});
請注意,您只能為封頂集合更新文檔,因此您無法插入您提到的額外字段。 您可能希望了解此處列舉的其他限制。
[編輯:在上一個文檔中添加更新嵌套字段。]
如果要更新第一個或最后一個文檔中的嵌套字段(分別在排序中使用1或-1),則可以獲取文檔,提取_id
,然后對該文檔執行原子更新。 像這樣的東西:
capped.find().sort([["_id", -1]]).limit(1).nextObject(function(err, item) {
if(err) throw err;
capped.update({ "_id": item._id },
{ "$set": { "timeCollected": 15, "publicIP.ip" : "127.0.0.1" }},
function(err, result) {
if(err) throw err;
console.log(result);
});
});
請注意,即使更新加蓋集合中文檔中存在的字段,也需要確保新值適合為文檔分配的空間。 因此,例如,將字符串值從"1"
更新為"127.0.0.1"
不一定有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.