要添加新字段,请在MongoDB中使用$addFields。让我们创建一个包含文档的集合-
> db.demo712.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea85f675d33e20ed1097b82") } > db.demo712.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea85f6a5d33e20ed1097b83") } > db.demo712.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea85f6e5d33e20ed1097b84") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo712.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John" } { "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris" } { "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob" }
以下是添加新字段的查询-
> db.demo712.aggregate([ ... { ... $addFields: ... { ... "TeacherName":"Robert" ... } ... } ... ] ... );
这将产生以下输出-
{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John", "TeacherName" : "Robert" } { "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris", "TeacherName" : "Robert" } { "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob", "TeacherName" : "Robert" }