J.K.A.
J.K.A.

Reputation: 7404

Distinct collection in mongodb with _id field

I've a collections like this:

{
    "_id" : ObjectId("5d5aa6b5cced8d2cac81e7d7"),
    "stream" : "Programming",
    "coursename" : "java",
    "fee" : 50000,
    "date" : ISODate("2019-08-19T13:40:05.312Z"),
    "__v" : 0
}

{
    "_id" : ObjectId("5d5aa6d2cced8d2cac81e7d8"),
    "stream" : "Basic",
    "coursename" : "Msoffice",
    "fee" : 50000,
    "date" : ISODate("2019-08-19T13:40:34.560Z"),
    "__v" : 0
}

{
    "_id" : ObjectId("5d5aa6e0cced8d2cac81e7d9"),
    "stream" : "Basic",
    "coursename" : "Tally",
    "fee" : 80000,
    "date" : ISODate("2019-08-19T13:40:48.667Z"),
    "__v" : 0
}

{
    "_id" : ObjectId("5d5aa707cced8d2cac81e7da"),
    "stream" : "Programming",
    "coursename" : "C++",
    "fee" : 80000,
    "date" : ISODate("2019-08-19T13:41:27.556Z"),
    "__v" : 0
}

Here you can see Programming and Basic streams are duplicate. I want to distinct stream along with _id and stream fields inside it. So result would be 2 collections. Ex:

{
    "_id" : ObjectId("5d5aa6b5cced8d2cac81e7d7"),
    "stream" : "Programming"
}
{
    "_id" : ObjectId("5d5aa6d2cced8d2cac81e7d8"),
    "stream" : "Basic"
}

distinct is returning only stream inside an array.

Upvotes: 1

Views: 66

Answers (1)

samuvel johnson
samuvel johnson

Reputation: 47

Using Mongodb aggregation $group and $project stages will give expected result

db.exampleCollection.aggregate([{$group:{_id:"$stream",stream_id:{$first:"$_id"}}},{$project:{stream:"$_id",_id:'$stream_id'}}]);

Example result mongo_aggregation_result

Upvotes: 1

Related Questions