3
{
    "_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();

1 Answer 1

4

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", ... ]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you felix, i just realized that i misspelled my array when i tried the same distinct option earlier... Hello monday!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.