Thomas
Thomas

Reputation: 12087

MongoDB / C# - Project as a dictionary

With this object:

class A
{
    string S;
    int V;
}

I am trying to do a projection like this (this won't compile)

Expression(_ => new KeyValuePair<string, int>() { _.S, _.V })

The goal being to get a Dictionary as an output.

Is there a way to do this?

I can do something like Include(_ => .s).Include( => .V).Exclude( => _._id) but, while I can cast that to a class, etc, I don't have a way to make this a dictionary; I can make it as a list, but I don't know how to assign S to key and V to value.

Upvotes: 2

Views: 1118

Answers (1)

sambomartin
sambomartin

Reputation: 6813

You don't need to project as dictionary, could you do something like this?

var listA = await GetCollection().As<A>().ToListAsync();
var dictA = listA.ToDictionary(_=>_S, _=>_.V);

You can control the projection on the db side by including this in the query

.Project(Builders<Entity>.Projection.Exclude("_id"))

Upvotes: 1

Related Questions