要用另一个字段更新数组,请使用$push。让我们创建一个包含文档的集合-
> db.demo283.insertOne({"Name":"Chris","Status":["Active","Inactive"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ab97ddd099650a5401a75")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo283.find();
这将产生以下输出-
{ "_id" : ObjectId("5e4ab97ddd099650a5401a75"), "Name" : "Chris", "Status" : [ "Active", "Inactive" ] }以下是使用另一个字段更新数组的查询-
> db.demo283.update({}, {$push: {Status:{$each:['Regular', 'NotRegular'], '$slice': -4}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })在find()方法的帮助下显示集合中的所有文档-
> db.demo283.find();
这将产生以下输出-
{ "_id" : ObjectId("5e4ab97ddd099650a5401a75"), "Name" : "Chris", "Status" : [ "Active", "Inactive", "Regular", "NotRegular" ]