Ruben Aguilar
Ruben Aguilar

Reputation: 1235

Translating MongoDb query to MongoDriver .Net core

I'm trying to translate the following MongoDb command to its equivalent in MongoDriver for .Net Core:

 db.test.aggregate([
  { 
     $project: {
        values: {
          $map: {
            input: { $objectToArray: "$foo" },
            as: "val",
            in: "$$val.v.value"
          }
        }
     }
  }
]);

But I'm having a bad time trying to understand the docs since I see a lot of references to types that my compiler cannot find (like AggregateArgs). What would be the best way of expressing it using C# syntax?

Upvotes: 0

Views: 194

Answers (1)

dododo
dododo

Reputation: 4847

Try this:

            var projectStage = BsonDocument.Parse(@"
        {
            'values' : {
                '$map' : {
                    'input' : {
                        '$objectToArray' : '$foo'
                    },
                    'as': 'val',
                    'in': '$$val.v.value'
                }
        }}");
        var coll = new MongoClient().GetDatabase("db").GetCollection<BsonDocument>("coll");
        var res = coll
            .Aggregate()
            .Project(projectStage)
            .ToList();

The generated projection query will be:

{
"$project": {
    "values": {
        "$map": {
            "input": {
                "$objectToArray": "$foo"
            },
            "as": "val",
            "in": "$$val.v.value"
        }
    }
}
}

Unfortunately, $objectToArray currently is not supported via the typed way. You can find how similar queries with typed way and LINQ can look like here: https://github.com/mongodb/mongo-csharp-driver/blob/master/tests/MongoDB.Driver.Tests/Linq/Translators/AggregateProjectTranslatorTests.cs

Upvotes: 1

Related Questions