要从MongoDB中的对象数组获取不同的值,请使用distinct()。让我们创建一个包含文档的集合-
> db.demo442.insertOne( ... { ... ... "Information" : [ ... { ... "FirstName" : "John", ... "Age" : 21 ... }, ... { ... "FirstName" : "Sam", ... "Age" : 23 ... }, ... { ... "FirstName" : "John", ... "Age" : 24 ... }, ... { ... "FirstName" : "Carol", ... "Age" : 20 ... }, ... { ... "FirstName" : "Sam", ... "Age" : 22 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e78cf29bbc41e36cc3caeb8") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo442.find();
这将产生以下输出-
{ "_id" : ObjectId("5e78cf29bbc41e36cc3caeb8"), "Information" : [ { "FirstName" : "John", "Age" : 21 }, { "FirstName" : "Sam", "Age" : 23 }, { "FirstName" : "John", "Age" : 24 }, { "FirstName" : "Carol", "Age" : 20 }, { "FirstName" : "Sam", "Age" : 22 } ] }
以下是从MongoDB中的对象数组获取不同值的查询-
> db.demo442.distinct("Information.FirstName");
这将产生以下输出-
[ "Carol", "John", "Sam" ]