如何在 MongoDB 中追加数组?
若要在 MongoDB 中追加数组,请使用 $concatArrays。我们创建一个带有文档的集合 -
> db.demo435.insertOne({"FirstName":["Chris"],"LastName":["Brown"]} ); { "acknowledged" : true, "insertedId" : ObjectId("5e7719b1bbc41e36cc3cae97") } > db.demo435.insertOne({"FirstName":["David"],"LastName":["Miller"]} ); { "acknowledged" : true, "insertedId" : ObjectId("5e7719bdbbc41e36cc3cae98") } > db.demo435.insertOne({"FirstName":["John"],"LastName":["Doe"]} ); { "acknowledged" : true, "insertedId" : ObjectId("5e7719c6bbc41e36cc3cae99") }
使用 find() 方法显示集合中的所有文档 -
> db.demo435.find().pretty();
这将产生以下输出 -
{ "_id" : ObjectId("5e7719b1bbc41e36cc3cae97"), "FirstName" : [ "Chris" ], "LastName" : [ "Brown" ] } { "_id" : ObjectId("5e7719bdbbc41e36cc3cae98"), "FirstName" : [ "David" ], "LastName" : [ "Miller" ] } { "_id" : ObjectId("5e7719c6bbc41e36cc3cae99"), "FirstName" : [ "John" ], "LastName" : [ "Doe" ] }
以下是在 MongoDB 中追加数组的查询 -
> db.demo435.aggregate([ { $project: { FullName: { $concatArrays: [ "$FirstName", "$LastName" ] } } } ])
这将产生以下输出 -
{ "_id" : ObjectId("5e7719b1bbc41e36cc3cae97"), "FullName" : [ "Chris", "Brown" ] } { "_id" : ObjectId("5e7719bdbbc41e36cc3cae98"), "FullName" : [ "David", "Miller" ] } { "_id" : ObjectId("5e7719c6bbc41e36cc3cae99"), "FullName" : [ "John", "Doe" ] }
广告