shirbr510
shirbr510

Reputation: 858

Performing Map in mongodb with C# driver

I've got an object (for an instance Person) that I want to map.

I want to perform something preety much like LINQ's Select method and return IEnumerable<ObjectId> instead of IEnumerable<Person>.

I've also found that the method I've been looking for is called map in mongodb terminology.

is there any equivalent that can be used with the C# driver?

Mongo Example: the mongo function I'm talking about is

db.getCollection('Persons').find({}).map( function(p) { return p._id; } );

Note: I already know of

var persons= await personsCollection.Find(_ => true).ToListAsync();
return persons.Select(p=>p._id);

but I'm looking for something "tidier" and that is already part of the mongodb driver.

EDIT

I'm looking for something beyond projections.

my code currently looks like this:

var personsCursor= personsCollection.Find(_ => true);
var personsProjection = personsCursor.Project<Person>(Builders<Person>.Projection.Include(p => p._id));
var personsIds = await personsProjection.ToListAsync();
return personsIds .Select(p => p._id.ToString());

Upvotes: 0

Views: 3023

Answers (2)

Felipe Augusto
Felipe Augusto

Reputation: 1563

to map properties in C#, you need to verify the official document from mongodb

https://mongodb.github.io/mongo-csharp-driver/2.7/reference/bson/mapping/

Upvotes: 0

MaKCbIMKo
MaKCbIMKo

Reputation: 2820

For this purpose you can use Projection;

From documentation:

Projecting Fields

Many times we don’t need all the data contained in a document. The Projection builder will help build the projection parameter for the find operation. Below we’ll exclude the “_id” field and output the first matching document:

var projection = Builders<BsonDocument>.Projection.Exclude("_id");
var document = await collection.Find(new BsonDocument()).Project(projection).FirstAsync();
Console.WriteLine(document.ToString());

And then, inside your own projection, you can specify which fields you need to return. If you go to the link above, you can find some documentation about the projection and mongo c# driver.

EDIT:

Also, you can use the projection builder to specify what you need to return:

var projection = Builders<BsonDocument>.Projection.Expression(d => d._id);
// and then put this projection to your query
var items = await collection.Find(new BsonDocument()).Project(projection).ToListAsync();

and now, each item should be represented only as _id.

Hope it will help.

Upvotes: 2

Related Questions