要推送数组,请在MongoDB中使用$push。首先让我们创建一个包含文档的集合-
> db.demo399.insertOne({Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5e610339fac4d418a017856d") } > db.demo399.insertOne({Name:"David",Age:22}); { "acknowledged" : true, "insertedId" : ObjectId("5e610341fac4d418a017856e") } > db.demo399.insertOne({Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5e610355fac4d418a017856f") } > db.demo399.insertOne({Name:"Bob",Age:23}); { "acknowledged" : true, "insertedId" : ObjectId("5e61035efac4d418a0178570") } > db.demo399.insertOne({Name:"David",Age:22}); { "acknowledged" : true, "insertedId" : ObjectId("5e610364fac4d418a0178571") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo399.find();
这将产生以下输出-
{ "_id" : ObjectId("5e610339fac4d418a017856d"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e610341fac4d418a017856e"), "Name" : "David", "Age" : 22 } { "_id" : ObjectId("5e610355fac4d418a017856f"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e61035efac4d418a0178570"), "Name" : "Bob", "Age" : 23 } { "_id" : ObjectId("5e610364fac4d418a0178571"), "Name" : "David", "Age" : 22 }
以下是推送数组的查询-
> db.demo399.aggregate( ... [ ... { ... $group: ... { ... _id: null, ... array: { $push: { Name: "$Name", Age: "$Age" } } ... } ... } ... ] ... )
这将产生以下输出-
{ "_id" : null, "array" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 }, { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 23 }, { "Name" : "David", "Age" : 22 } ] }