使用聚合框架将字符串添加到MongoDB中的整个列。首先让我们创建一个包含文档的集合-
> db.prependDemo.insertOne({"StudentFirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3bcedceb9a92e6aa1955") } > db.prependDemo.insertOne({"StudentFirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3bd3dceb9a92e6aa1956") } > db.prependDemo.insertOne({"StudentFirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ccf3bd8dceb9a92e6aa1957") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.prependDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ccf3bcedceb9a92e6aa1955"), "StudentFirstName" : "John" } { "_id" : ObjectId("5ccf3bd3dceb9a92e6aa1956"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ccf3bd8dceb9a92e6aa1957"), "StudentFirstName" : "Robert" }
这是将字符串添加到MongoDB中整个列的查询-
> db.prependDemo.aggregate([{ ... $project: { ... "StudentFirstName": { ... $concat: ["Mr.", "$StudentFirstName"] ... } ... } ... }]);
这将产生以下输出-
{ "_id" : ObjectId("5ccf3bcedceb9a92e6aa1955"), "StudentFirstName" : "Mr.John" } { "_id" : ObjectId("5ccf3bd3dceb9a92e6aa1956"), "StudentFirstName" : "Mr.Chris" } { "_id" : ObjectId("5ccf3bd8dceb9a92e6aa1957"), "StudentFirstName" : "Mr.Robert" }