Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting distinct values from object array MongoDB

Tags:

mongodb

{
    "_id" : NUUID("f5050a5d-b3be-4de6-a135-a119436fb511"),
    "CoursesData" : [ 
        {
            "Name" : "Naturgræs",
            "Value" : 1
        }
    ],
    "FacilityType" : {
        "_id" : NUUID("a1b4844b-518b-40e2-8aa5-8ee399ac2d4e")
    }
}

I want to retrieve a list with the distinct values from the field Name inside my object array of CourseData. Filtered by FacilityType._id. I tried using both $facet and the distinct operator, but it doesn't seems to like object arrays.

My result should look like this (or similar):

FacilityType (a1b4844b-518b-40e2-8aa5-8ee399ac2d4e),
CourseData: [Name1, Name2, Name3]

Update

From the answer given below, this is how you do it with the C# driver, if anyone needs to do the same.

  FieldDefinition<FacilityDocument, string> field = "CoursesData.Name";

  var result = FacilityCollection.Distinct(field, Builders<FacilityDocument>.Filter.Eq(x => x.FacilityType.ID, new Guid("a1b4844b-518b-40e2-8aa5-8ee399ac2d4e"))).ToList();
like image 645
mp1990 Avatar asked Dec 19 '25 21:12

mp1990


1 Answers

You can use distinct(). It will return distinct element for a specific field from document which match a query

For example if you want distinct value of Name field for facility "a1b4844b-518b-40e2-8aa5-8ee399ac2d4e", run this query:

db.collection.distinct("CoursesData.Name", {"FacilityType._id": "a1b4844b-518b-40e2-8aa5-8ee39ac2d4e"})

it will return :

[ "Naturgræs", ... ]
like image 180
felix Avatar answered Dec 22 '25 14:12

felix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!