合并MongoDB中的数组中的非重复项?
要合并来自数组中的唯一项,请在 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 ] }
广告