在变量中获取值的麻烦

时间:2017-01-10 21:18:02

标签: c# .net mongodb mongodb-query mongodb-.net-driver

基本上这是我的代码,我遇到了麻烦。对mongoDB非常陌生,并且很想了解如何从变量'line'中返回的JSON字符串中获取值。

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;
        }

如果我返回行,这是我得到的输出:

  

{“_ id”:ObjectId(“58746dcafead398e4d7233f5”),“movie_name”:“Hemin”   }

我希望能够将'Hemin'值取为'a'。

2 个答案:

答案 0 :(得分:1)

我知道这不是你要求的,但是因为你正在使用c#驱动程序,所以我会推荐以下内容。假设您有一个与metacorp集合对应的c#类或至少一个处理它的序列化程序。希望它有所帮助。

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;

答案 1 :(得分:1)

你可以让电影的dto课只从集合中获取数据:

public class Movie
{
    public ObjectId Id { get; set; }
    public string movie_name { get; set;}
}

...

var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");

var movies = collection.Find(x=>x.movie_name == "Hemin").ToEnumerable();