难以在 MongoDB 中实现 $addToSet 以获取单个字段的值?
$$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" ] }
广告