要合并,请使用$setUnion运算符。首先让我们创建一个包含文档的集合-
> db.mergeTwoArrayFieldDemo.insertOne({"NaturalNumbers":[1,2,3,8,10,20,30],"WholeNumbers":[0,1,2,63,78,20,45]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68e4057806ebf1256f11d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.mergeTwoArrayFieldDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "NaturalNumbers" : [ 1, 2, 3, 8, 10, 20, 30 ], "WholeNumbers" : [ 0, 1, 2, 63, 78, 20, 45 ] }
以下是在MongoDB中合并两个数组字段的查询。
> db.mergeTwoArrayFieldDemo.aggregate([ { "$project": { "MergedArray": { "$setUnion": [ "$NaturalNumbers", "$WholeNumbers" ] } }} ]);
这将产生以下输出-
{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "MergedArray" : [ 0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78 ] }