您可以在的帮助下合并结果forEach()
。首先让我们创建一个包含文档的集合-
> db.concatenateDemo.insertOne({"Name":"John","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cc80dd88f9e6ff3eb0ce448") } > db.concatenateDemo.insertOne({"Name":"Carol","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cc80de18f9e6ff3eb0ce449") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.concatenateDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc80dd88f9e6ff3eb0ce448"), "Name" : "John", "Age" : 21 } { "_id" : ObjectId("5cc80de18f9e6ff3eb0ce449"), "Name" : "Carol", "Age" : 23 }
这是连接结果的查询-
> db.concatenateDemo.find().forEach( function (result) {result.NameAndAge = result.Name + ' ' + result.Age; printjson(result); } );
这将产生以下输出-
{ "_id" : ObjectId("5cc80dd88f9e6ff3eb0ce448"), "Name" : "John", "Age" : 21, "NameAndAge" : "John 21" } { "_id" : ObjectId("5cc80de18f9e6ff3eb0ce449"), "Name" : "Carol", "Age" : 23, "NameAndAge" : "Carol 23" }