前两篇我们介绍了更新一个文档和多个文档;本篇我们介绍替换一个文档,具体语法如下:
db.collection.replaceOne(filter, replacement, options)
其中,
collection指的是集合名称
filter指的是过滤条件
replacement指的是替换的文档
options指的是其他的一些选项
这里不再介绍filter, options
如果需要对filter进行详细的了解可以参考: MongoDB 查询文档(1)https://blog.csdn.net/m1729339749/article/details/129965699
MongoDB 查询文档(2)https://blog.csdn.net/m1729339749/article/details/129971708 如果需要对options进行详细的了解可以参考: MongoDB 更新文档(更新一条文档)https://blog.csdn.net/m1729339749/article/details/129983304下面我们还是以示例直接展示如何替换一个文档:
例子:
首先查询一下所有文档:
{ "_id" : "1001", "name" : "张三2", "fruits" : [ "apple", "orange" ], "updateTime" : ISODate("2023-04-06T02:36:00.703Z") }
{ "_id" : "1002", "name" : "李四", "fruits" : [ "banana", "apple" ] }
{ "_id" : "1003", "name" : "王五", "fruits" : [ "banana", "apple", "orange" ] }
{ "_id" : "1004", "score" : 100, "name" : "田七", "fruits" : [ "banana" ] }
{ "_id" : "1005", "name" : "田七", "score" : 100, "fruits" : [ "banana" ] }
下面我们替换名字为田七的文档:
db.test.replaceOne({ "name": "田七" }, { "commet": "我的内容被替换了" }
);
查询的文档如下:
{ "_id" : "1001", "name" : "张三2", "fruits" : [ "apple", "orange" ], "updateTime" : ISODate("2023-04-06T02:36:00.703Z") }
{ "_id" : "1002", "name" : "李四", "fruits" : [ "banana", "apple" ] }
{ "_id" : "1003", "name" : "王五", "fruits" : [ "banana", "apple", "orange" ] }
{ "_id" : "1004", "commet" : "我的内容被替换了" }
{ "_id" : "1005", "name" : "田七", "score" : 100, "fruits" : [ "banana" ] }
可以看到除_id外,文档被替换掉了;另外一条_id为1005的文档没有被替换掉,说明只能替换一条文档。