我在页面里面写了一个方法,通过Mongodb的["_id"]来查找记录
而Mongodb的["_id"]的值在cmd命令里面看的到格式是 "_id" : ObjectId("4e089a6ec6c7e91b6cf2e50d")
我后台获取的Mongodb的["_id"]值为"4e089a6ec6c7e91b6cf2e50d";
所以无法匹配ObjectId("4e089a6ec6c7e91b6cf2e50d")的格式,所以一直查找不到数据,
使用过mongodb的大哥帮我解决下,谢谢了
下面是代码:
public List GetUserFriendByuserId(object id)
{
try
{
// strid = userid;
DateTime BeginTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
list = new List();
// MongoDB连接串,以[mongodb://]开头。这里,我们连接的是本机的服务
string connectionString = "mongodb://192.168.1.112:27017";
// 连接到一个MongoServer上
MongoServer server = MongoServer.Create();
// -------------------------------------------------------------------------
// 打开数据库MonDB
MongoDatabase db = server.GetDatabase("MonDB");
// 获取集合BsonDocument
MongoCollection[B] collection = db.GetCollection[B]("FriendsNews");
// -------------------------------------------------------------------------
// 查询上面那个刚刚插进去的数据,就这格式了,看看QueryDocument的文档吧
QueryDocument query = new QueryDocument();
query.Add("_id",id);//查询条件对象赋值
int it = collection.Count();
// 遍历结果
foreach (BsonDocument emp in collection.Find(query))
{
// BsonValue有两种取值方式,下面两个都用了一个是AsXXX,一个是ToXXX
// Console.WriteLine("name:{0}\ttitle:{1}", emp["userid"].AsString, emp["fridenid"].ToString());
FriendsNews info = new FriendsNews();
info._id = emp["_id"].ToString();
info.userid = emp["userid"].ToString();
info.fridenid = emp["fridenid"].ToString();
info.title = emp["title"].ToString();
list.Add(info);
}
server.Disconnect();//关闭连接
DateTime endTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
TimeSpan t = endTime.Subtract(BeginTime);
this.Label10.Text = "总共用了" + t.TotalSeconds * 1000 + "毫秒";
}
catch
{
this.Label8.Text = "失败";
this.Btn_Down.Visible = false;
this.Btn_Up.Visible = false;
this.Label1.Visible = false;
}
return list;
// return collection;
}
|
|