除非该值已存在,否则$addToSet运算符会将值添加到数组,在这种情况下,$addToSet对该数组不执行任何操作。
让我们创建一个包含文档的集合-
> db.demo533.insertOne({"ProjectName":"Online Hospital Management"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4cfaef4dcbee04fbbbfc") } > db.demo533.insertOne({"ProjectName":"Online Library Management"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4d02ef4dcbee04fbbbfd") } > db.demo533.insertOne({"ProjectName":"Online Hospital Management"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4d04ef4dcbee04fbbbfe") } > db.demo533.insertOne({"ProjectName":"Online Customer Tracker"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4d0def4dcbee04fbbbff") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo533.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8b4cfaef4dcbee04fbbbfc"), "ProjectName" : "Online Hospital Management" } { "_id" : ObjectId("5e8b4d02ef4dcbee04fbbbfd"), "ProjectName" : "Online Library Management" } { "_id" : ObjectId("5e8b4d04ef4dcbee04fbbbfe"), "ProjectName" : "Online Hospital Management" } { "_id" : ObjectId("5e8b4d0def4dcbee04fbbbff"), "ProjectName" : "Online Customer Tracker" }
以下是实现$addToSet并获取字段ProjectName的值的查询-
> db.demo533.aggregate( ... [ ... { ... $group: ... { ... _id:null, ... SetOfProject: { $addToSet: "$ProjectName" } ... } ... } ... ] ... )
这将产生以下输出-
{ "_id" : null, "SetOfProject" : [ "Online Customer Tracker", "Online Library Management", "Online Hospital Management" ] }