1

I have my data in MongoDB that looks like this:

_id:ObjectId("59d33718050bad45ec6e6f53")
Timestamp:2017-10-03 15:07:04.145
ID:"915110933730439169"
Content:"Turn on the light"
DateCreated:2017-05-12 00:00:00.000
UserID:"862903658828017666"
Username:"Johnny"

And I only need the "Content" data in one of my classes, and I have to assign those content into a generic list. (I have no idea of how much the data would be). So I look around online and I have done the Deserialization of the Bson object into class, but then I have no idea how to assign only "content" inside the list because only the "content" will work on other purposes in this class.

Below are my code of this class:

class Analysis
{
    public static void RetrieveData()
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var database = client.GetDatabase("TrainData");
        var collection = database.GetCollection<BsonDocument>("Sample1");

        List<string> streamdata = new List<string>();

        var filter = new BsonDocument();
        var cursor = collection.FindAsync(filter).Result;
        cursor.ForEachAsync(batch =>
        {
            streamdata.Add(BsonSerializer.Deserialize<string>(batch));
        });

    }

public class StreamData
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string Content { get; set; }
    public string ID { get; set; }
    public DateTime DateCreated { get; set; }
    public string UserID { get; set; }
    public string Username { get; set; }
}

May I know where did I missing or what else I have to added in order to let me insert the "content" into the generic list? Thank you.

1 Answer 1

2

You may try to use projection to get the "Content" data only.

        var data = collection.Aggregate().Project<BsonDocument>(Builders<BsonDocument>.Projection.Exclude(f => f["_id"]).Include(f => f["Content"])).ToList();

        List<string> streamdata = new List<string>();

        foreach(var d in data)
        {
            streamdata.Add(d["Content"].AsString);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

It works!!! I get to display all the content! Thank you so much I've been searching around for one whole day for this solution!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.