Getting a distinct aggregation of an array field across indexes


To get a distinct aggregation of an array field across indexes, let us take an example and create a collection with some documents.

Following is the query to create a collection with documents

> db.distinctAggregation.insertOne({"UserName":"Larry","UserPost":["Hi","Hello"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98aefb330fd0aa0d2fe4c6")
}
> db.distinctAggregation.insertOne({"UserName":"Chris","UserPost":["Hi","Good Morning"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98af0a330fd0aa0d2fe4c7")
}
> db.distinctAggregation.insertOne({"UserName":"Robert","UserPost":["Awesome"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98af1e330fd0aa0d2fe4c8")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c98aefb330fd0aa0d2fe4c6"),
   "UserName" : "Larry",
   "UserPost" : [
      "Hi",
      "Hello"
   ]
}
{
   "_id" : ObjectId("5c98af0a330fd0aa0d2fe4c7"),
   "UserName" : "Chris",
   "UserPost" : [
      "Hi",
      "Good Morning"
   ]
}
{
   "_id" : ObjectId("5c98af1e330fd0aa0d2fe4c8"),
   "UserName" : "Robert",
   "UserPost" : [
      "Awesome"
   ]
}

Following is the query to create index on array field

> db.distinctAggregation.ensureIndex({"UserPost":1});
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

Following is the query to get a distinct aggregation of an array field across indexes

> db.distinctAggregation.distinct("UserPost");

This will produce the following output

[ "Awesome", "Good Morning", "Hello", "Hi" ]

Updated on: 30-Jul-2019

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements