獲取 MongoDB 中更新文件的數量?


要獲取 MongoDB 中更新的文件數,你需要結合使用 runCommand 和 getlasterror。

我們先使用文件建立一個集合

> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca28c1d6304881c5ce84bad")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca28c226304881c5ce84bae")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca28c276304881c5ce84baf")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Ramit"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca28c366304881c5ce84bb0")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca28c436304881c5ce84bb1")
}

以下是使用 find() 方法顯示集合中所有文件的查詢

> db.getNumberOfUpdatedDocumentsDemo.find().pretty();

將產生以下輸出

{ "_id" : ObjectId("5ca28c1d6304881c5ce84bad"), "StudentName" : "David" }
{ "_id" : ObjectId("5ca28c226304881c5ce84bae"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5ca28c276304881c5ce84baf"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5ca28c366304881c5ce84bb0"), "StudentName" : "Ramit" }
{ "_id" : ObjectId("5ca28c436304881c5ce84bb1"), "StudentName" : "Adam" }

以下是更新文件的查詢

> db.getNumberOfUpdatedDocumentsDemo.update({}, {$set : {"StudentName" : "Carol"}}, true, true);
WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 })
Now, get the number of updated documents:
> db.runCommand( "getlasterror" );

以下是以 n=5 顯示的輸出,即已更新 5 個文件

{
   "connectionId" : 4,
   "updatedExisting" : true,
   "n" : 5,
   "syncMillis" : 0,
   "writtenTo" : null,
   "err" : null,
   "ok" : 1
}

現在顯示集合中的所有文件

> db.getNumberOfUpdatedDocumentsDemo.find().pretty();

將產生以下輸出

{ "_id" : ObjectId("5ca28c1d6304881c5ce84bad"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c226304881c5ce84bae"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c276304881c5ce84baf"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c366304881c5ce84bb0"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c436304881c5ce84bb1"), "StudentName" : "Carol" }

更新於:2019-07-30

201 次瀏覽

啟動你的 職業

完成課程取得認證

開始
廣告
© . All rights reserved.