MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBのupdate()関数内でインクリメントするにはどうすればよいですか?


$inc演算子を使用してインクリメントできます。まず、ドキュメントを使用してコレクションを作成しましょう-

> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Chris","PlayerScore":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b3f4345990cee87fd893")
}
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Robert","PlayerScore":88});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b3fc345990cee87fd894")
}
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"David","PlayerScore":99});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b407345990cee87fd895")
}

以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-

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

これにより、次の出力が生成されます-

{
   "_id" : ObjectId("5cd2b3f4345990cee87fd893"),
   "PlayerName" : "Chris",
   "PlayerScore" : 78
}
{
   "_id" : ObjectId("5cd2b3fc345990cee87fd894"),
   "PlayerName" : "Robert",
   "PlayerScore" : 88
}
{
   "_id" : ObjectId("5cd2b407345990cee87fd895"),
   "PlayerName" : "David",
   "PlayerScore" : 99
}

以下は、MongDBのupdate()関数内で加算を実行するためのクエリです-

> db.addInUpdateFunctionDemo.update({_id : ObjectId("5cd2b407345990cee87fd895")},{$inc: {PlayerScore: 201}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

すべてのドキュメントをもう一度確認しましょう-

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

これにより、次の出力が生成されます-

{
   "_id" : ObjectId("5cd2b3f4345990cee87fd893"),
   "PlayerName" : "Chris",
   "PlayerScore" : 78
}
{
   "_id" : ObjectId("5cd2b3fc345990cee87fd894"),
   "PlayerName" : "Robert",
   "PlayerScore" : 88
}
{
   "_id" : ObjectId("5cd2b407345990cee87fd895"),
   "PlayerName" : "David",
   "PlayerScore" : 300
}

  1. MongoDBのレコードを更新するにはどうすればよいですか?

    レコードを更新するには、_idに基づいて更新する必要があります。ドキュメントを使用してコレクションを作成しましょう- > db.demo458.insertOne( {_id:101,"Name":"David" } ); { "acknowledged" : true, "insertedId" : 101 } > db.demo458.insertOne( {_id:102,"Name":"Chris" } ); { "acknowledged&qu

  2. MongoDBの配列内の要素を更新しますか?

    配列内の要素を更新するには、MongoDBで$setを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo494.insertOne( ... { ... ...    "CollegeDetails" : [ ...       { ...          "CollegeName" : "MIT", ...          "Fee