Projection result as an array of selected items in MongoDB?


Use the distinct() for this, since it finds the distinct values for a specified field across a single collection or view and returns the results in an array.

Let us first create a collection with documents −

> db.projectionListDemo.insertOne({"_id":"1","Subject":["MongoDB","MySQL","Java"]});
{ "acknowledged" : true, "insertedId" : "1" }
> db.projectionListDemo.insertOne({"_id":"2","Subject":["MongoDB","C","C++"]});
{ "acknowledged" : true, "insertedId" : "2" }
> db.projectionListDemo.insertOne({"_id":"3","Subject":["Java","Python"]});
{ "acknowledged" : true, "insertedId" : "3" }

Display all documents from a collection with the help of find() method −

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

Output

{ "_id" : "1", "Subject" : [ "MongoDB", "MySQL", "Java" ] }
{ "_id" : "2", "Subject" : [ "MongoDB", "C", "C++" ] }
{ "_id" : "3", "Subject" : [ "Java", "Python" ] }

Now, let us get result as an array of selected items −

> db.projectionListDemo.distinct('_id', {'Subject' : 'MongoDB'});

Output

[ "1", "2" ]
raja
Published on 14-Jun-2019 14:13:53
Advertisements