Search code examples
c#.netmongodbmongodb-querymongodb-.net-driver

Trouble Fetching Value in Variable


Basically here's my code which I'm having trouble with. Insanely new to mongoDB and would love to understand how to get values out of a JSON string that is returns in the variable 'line'.

public string get_data()
        {
            var client = new MongoClient();
            var db = client.GetDatabase("test");
            var collection = db.GetCollection<BsonDocument>("metacorp");
            var cursor = collection.Find("{'movie_name' : 'Hemin'}").ToCursor();
            var line = "";
            foreach (var document in cursor.ToEnumerable())
            {
                using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonWriter(stringWriter))
                {
                    var context = BsonSerializationContext.CreateRoot(jsonWriter);
                    collection.DocumentSerializer.Serialize(context, document);
                    line = stringWriter.ToString();

                }
            }
            var js = new JavaScriptSerializer();
            var d = js.Deserialize<dynamic>(line);
            var a  = d["movie_name"];
            return line;
        }

This is the output I get if I return line:

{ "_id" : ObjectId("58746dcafead398e4d7233f5"), "movie_name" : "Hemin" }

I want to be able to fetch the value 'Hemin' into 'a'.


Solution

  • I know this is not what you're asking for but since you're using the c# driver then I would recommend the following. Assumes you have a c# class corresponding to metacorp collection or at least a serializer that handles it. Hope it helps.

    var client = new MongoClient();
    var db = client.GetDatabase("test");
    var collection = db.GetCollection<MetaCorp>("metacorp");
    var m = collection.SingleOrDefault(x => x.Movie_Name == "Hemin"); // Assuming 0 or 1 with that name. Use Where otherwise
    var movieName = "Not found";
    if(m!= null)
       movieName = m.Movie_Name;