要合并数组中的唯一项,请在MongoDB中使用Aggregate()。让我们创建一个包含文档的集合-
> db.demo420.insert( ... { ... ... "details" : [ ... { ... "Value1":10, ... "Value2":20, ... "Value3":30 ... } ... ] ... } ... ) WriteResult({ "nInserted" : 1 }) > db.demo420.insert( ... { ... ... "Info" : [ ... { ... "Value1":10, ... "Value2":20, ... "Value3":300 ... } ... ] ... } ... ) WriteResult({ "nInserted" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo420.find();
这将产生以下输出-
{ "_id" : ObjectId("5e739a569822da45b30346dc"), "details" : [ { "Value1" : 10, "Value2" : 20, "Value3" : 30 } ] } { "_id" : ObjectId("5e739a569822da45b30346dd"), "Info" : [ { "Value1" : 10, "Value2" : 20, "Value3" : 300 } ] }
以下是合并数组中唯一项的查询-
> db.demo420.aggregate([ ... { "$project": { ... "_id": 0, ... "unique": { ... "$filter": { ... "input": { ... "$setDifference": [ ... { "$concatArrays": [ ... "$Info.Value1", ... "$Info.Value2", ... "$Info.Value3" ... ... ]}, ... [] ... ] ... }, ... "cond": { "$ne": [ "$$this", "" ] } ... } ... } ... }}, ... { "$unwind": "$unique" }, ... { "$group": { ... "_id": null, ... "uniqueArray": { "$addToSet": "$unique" } ... }} ... ])
这将产生以下输出-
{ "_id" : null, "uniqueArray" : [ 300, 20, 10 ] }