[英]How can I take data from mongodb by filtering with bson id it with web api asp .net?
I would like prepare Employee Detail page with asp.net web api. 我想使用asp.net Web API准备“员工详细信息”页面。 And I wanted to take data from mongodb and filter it according to id.
我想从mongodb中获取数据并根据ID对其进行过滤。 But 'null' value appearing on the page.
但是“ null”值出现在页面上。 What can I do for fixing the problem?
我该如何解决该问题? Can you give me an idea?
你能给我个主意吗? Thank you in advance.
先感谢您。
My Employee Detail page is 我的员工详细信息页面是
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MongoDB.Driver; using MongoDB.Bson; using TESTMONGO_C.Models; using System.Configuration; namespace TESTMONGO_C.Controllers { public class EmployeeDetailDataController : ApiController { [HttpGet] public object GetEmployeeById(string id) { string constr = ConfigurationManager.AppSettings["connectionString"]; var Client = new MongoClient(constr); var DB = Client.GetDatabase("test"); var collection = db.GetCollection<EmployeeDetail>("employee").Find(new BsonDocument("_id",ObjectId.Parse(id))).ToList(); return Json(collection); } } }
My EmployeeDetail model is 我的EmployeeDetail模型是
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TESTMONGO_C.Models { public class EmployeeDetail { [BsonRepresentation(BsonType.ObjectId)] public string id { get; set; } public string name { get; set; } public string department { get; set; } public string address { get; set; } public string city { get; set; } public string country { get; set; } } }
Try following: 请尝试以下操作:
[HttpGet]
public object GetEmployeeById(string id)
{
string constr = ConfigurationManager.AppSettings["connectionString"];
var Client = new MongoClient(constr);
var DB = Client.GetDatabase("test");
var collection = DB.GetCollection<EmployeeDetail>("employee");
return Json(collection.Find(new BsonDocument("id", id)).ToList());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.