Computer >> Máy Tính >  >> Lập trình >> MongoDB

Nhận số lượng tài liệu cập nhật trong MongoDB?

Để nhận số lượng tài liệu cập nhật trong MongoDB, bạn cần sử dụng runCommand cùng với getlasterror.

Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu

> 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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ():

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

Điều này sẽ tạo ra kết quả sau

{ "_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" }

Sau đây là truy vấn cập nhật tài liệu

> 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" );

Sau đây là kết quả hiển thị n =5 tức là 5 tài liệu đã được cập nhật

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

Bây giờ, hãy hiển thị tất cả tài liệu từ một bộ sưu tập

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

Điều này sẽ tạo ra kết quả sau

{ "_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" }