1

The documents look like this:

{
  Age: 20,
  Gender: "Male",
  SomeField: "ABC"
  SomeParameter: 17.7
}

With C# mongodb driver, how do you write something like this?

SELECT Age, Gender, MIN(SomeParameter), MAX(SomeParameter)
FROM ...
WHERE SomeField = 'ABC'
GROUP BY Age, Gender

So that for each combination (group) of Gender and Age we'll get min & max of SomeParameter

1 Answer 1

1

The key to this is in the "_id" value construction:

IMongoCollection<BsonDocument> collection = GetYourCollectionHere();

// there are many ways to create a filter. Using Builders here.
var filter = Builders<BsonDocument>.Filter.Eq("SomeField", "ABC"); 

var groupby = new BsonDocument("_id", new BsonDocument {
                        { "Gender", "$Gender" },
                        { "Age", "$Age" }
                })
                .Add("Min", new BsonDocument("$min", "$SomeParameter"))
                .Add("Max", new BsonDocument("$max", "$SomeParameter"));

var result = collection
                .Aggregate()
                .Match(filter)
                .Group(groupby);

// to see the output
foreach (var doc in result)
{
    Console.WriteLine(doc.ToJson());
}
Sign up to request clarification or add additional context in comments.

Comments

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.