Search code examples
c#mongodbmongodb-.net-driver

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());

Solution

  • 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.