如何更新或修改 MongoDB 中集合的现有文档?
要更新或修改MongoDB中集合的现有文档,您需要使用update()方法。语法如下:
db.yourCollectionName.update(yourExistingValue, yourUpdatedValue);
在这里,我们将创建一个名为updateinformation的集合。创建集合的查询如下。当您使用insert()如下所示的方法插入一些文档时,MongoDB会自动创建一个集合:
> db.updateInformation.insert({"StudentName":"Larry",StudentAge:35,StudentMarks:89});以下是输出:
WriteResult({ "nInserted" : 1 })现在您可以借助find()来自集合更新信息的方法来显示文档。查询如下:
> db.updateInformation.find();
以下是显示我们上面添加的集合中的文档的输出:
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 35,
"StudentMarks" : 89 }现在,让我们更新或修改现有文档'StudentAge'35到24。为此,我们将使用该update()方法。查询如下:
> db.updateInformation.update({StudentAge:35},{$set:{StudentAge:24}});以下是输出:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })我们已将上面的StudentAge35更新为24。让我们再次检查文件。查询如下:
> db.updateInformation.find().pretty();
以下是输出:
{
"_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"),
"StudentName" : "Larry",
"StudentAge" : 24,
"StudentMarks" : 89
}查看上面的StudentAge字段。年龄现在更新为24/以前是35。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下