Reputation: 27
I try to retrieve specific element from data base collection.
collection.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X));
This code give something like this:
{ "_id" : ObjectId("599d420bf2e1abfed53fe3c6"), "no" : 9, "word" : "write" }
{ "_id" : ObjectId("599d420bf2e1abfed53fe3c8"), "no" : 10, "word" : "first" }
{ "_id" : ObjectId("599d420bf2e1abfed53fe3ca"), "no" : 11, "word" : "water" }
but I want to see only:
write
first
water
How can I do that? Thanks
Upvotes: 1
Views: 371
Reputation: 343
Since I don't know what your data looks like, I've created my own as a test sample so you can see how I use projections to solve the problem. As you can see I've created a simple test collection call books that has a document with the property Word in it. It also has the implied "_id" property I created a small sample application in LINQPad to demonstrate.
// Define other methods and classes here
class Book
{
public ObjectId _id { get; set; }
public string Word { get; set; }
}
void Main()
{
var mongoConnectionString = @"mongodb://Topaz:p%40$$w0rd@localhost";
var client = new MongoDB.Driver.MongoClient(mongoConnectionString);
var db = client.GetDatabase("Test");
var col = db.GetCollection<Book>("Books");
var filter = Builders<Book>.Filter.Empty;
var projection = Builders<Book>.Projection.Expression(m => m.Word);
var options = new FindOptions<Book, String> { BatchSize = 256, Projection = projection };
var results = new List<string>();
using (var cursor = col.FindAsync(filter, options).Result)
{
while (cursor.MoveNextAsync().Result)
{
var batch = cursor.Current as IList<String>;
results.AddRange(batch);
}
}
results.ForEach(a => Console.WriteLine(a));
}
Here is the output that I get.
Foo Bar
I hope this helps you. If it does, please mark my answer and let me know in a comment. Thank you.
Upvotes: 1