在MongoDB中的多个字段上执行不同的操作?
您可以将$group运算符与聚合框架一起使用,以在多个字段上执行不同的操作。首先让我们创建一个包含文档的集合-
> db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "Chris", ... "StudentAge" : 21, ... "StudentCountryName": "US" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d7") } > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "Robert", ... "StudentAge" : 21, ... "StudentCountryName": "AUS" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d8") } > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "Chris", ... "StudentAge" : 22, ... "StudentCountryName": "UK" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d9") } > db.distinctOnMultipleFieldsDemo.insertOne( ... { ... "StudentFirstName" : "David", ... "StudentAge" : 24, ... "StudentCountryName": "AUS" ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2e518b64f4b851c3a13da") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.distinctOnMultipleFieldsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd2e518b64f4b851c3a13d7"), "StudentFirstName" : "Chris", "StudentAge" : 21, "StudentCountryName" : "US" } { "_id" : ObjectId("5cd2e518b64f4b851c3a13d8"), "StudentFirstName" : "Robert", "StudentAge" : 21, "StudentCountryName" : "AUS" } { "_id" : ObjectId("5cd2e518b64f4b851c3a13d9"), "StudentFirstName" : "Chris", "StudentAge" : 22, "StudentCountryName" : "UK" } { "_id" : ObjectId("5cd2e518b64f4b851c3a13da"), "StudentFirstName" : "David", "StudentAge" : 24, "StudentCountryName" : "AUS" }
以下是对MongoDB中的多个字段执行不同查询的查询-
> db.distinctOnMultipleFieldsDemo.aggregate([ ... { ... $group: ... { ... _id:0, ... StudentFirstName: {$addToSet: '$StudentFirstName'}, ... StudentAge: {$addToSet: '$StudentAge'}, ... StudentCountryName: {$addToSet: '$StudentCountryName'}, ... }} ... ]);
这将产生以下输出-
{ "_id" : 0, "StudentFirstName" : [ "David", "Robert", "Chris" ], "StudentAge" : [ 24, 22, 21 ], "StudentCountryName" : [ "UK", "AUS", "US" ] }