首页 文章资讯内容详情

在一个MongoDB文档中获取两个数组中的唯一值

2026-06-04 1 花语

要在文档的两个数组中获取唯一值,请在aggregate()中使用$setUnion。的$setUnion采用两个或多个阵列,并返回包含出现在任何输入数组元素的数组。

让我们创建一个包含文档的集合-

>db.demo608.insertOne({"ListOfName1":["John","Chris","Bob","David"],"ListOfName2":["Bob", "Sam","John","Robert","Chris"]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e974542f57d0dc0b182d62b") }

在find()方法的帮助下显示集合中的所有文档-

> db.demo608.find().pretty();

这将产生以下输出-

{ "_id" : ObjectId("5e974542f57d0dc0b182d62b"), "ListOfName1" : [ "John", "Chris", "Bob", "David" ], "ListOfName2" : [ "Bob", "Sam", "John", "Robert", "Chris" ] }

以下是查询以在一个MongoDB文档中的两个数组中获取唯一值-

> db.demo608.aggregate([ ... {$project:{SetOfNames:{$setUnion:[$ListOfName1,$ListOfName2]}}} ... ]).pretty();

这将产生以下输出-

{ "_id" : ObjectId("5e974542f57d0dc0b182d62b"), "SetOfNames" : [ "Bob", "Chris", "David", "John", "Robert", "Sam" ] }