MongoDB-内存中BsonDocument中的查询
我正在将单个文档读入BsonDocument对象。从MongoDB中读取文档后,我想在内存中查询该文档。 我的医生是这样的:MongoDB-内存中BsonDocument中的查询,mongodb,mongodb-.net-driver,Mongodb,Mongodb .net Driver,我正在将单个文档读入BsonDocument对象。从MongoDB中读取文档后,我想在内存中查询该文档。 我的医生是这样的: { "_id": { "$binary": "DYibd4bSz0SFXTTmY46gOQ==", "$type": "03" }, "title": "XYZ 2011", "pages": [ { "pagetype": "contactcapture", "pagetitle": "Contact",
{
"_id": {
"$binary": "DYibd4bSz0SFXTTmY46gOQ==",
"$type": "03"
},
"title": "XYZ 2011",
"pages": [
{
"pagetype": "contactcapture",
"pagetitle": "Contact",
"questions": [
{
"qtype": "text",
"text": "Firstname",
"name": "firstname"
},
{
"qtype": "text",
"text": "Surname",
"name": "surname"
},
{
"qtype": "text",
"text": "Company",
"name": "companyname"
}
]
},
{
"pagetype": "question",
"pagetitle": "Question 1",
"questions": [
{
"qtype": "radio",
"text": "What drink?",
"name": "drink",
"answers": [
{
"text": "Tea"
},
{
"text": "Coffee"
},
{
"text": "Hot chocolate"
},
{
"text": "Water"
}
]
}
]
},
{
"pagetype": "question",
"pagetitle": "Question 2",
"questions": [
{
"qtype": "check",
"text": "Accompaniments?",
"name": "accompaniments",
"answers": [
{
"text": "Nuts"
},
{
"text": "Crisps"
},
{
"text": "Biscuits"
}
]
}
]
},
{
"pagetype": "question",
"pagetitle": "Question 3",
"questions": [
{
"qtype": "radio",
"text": "When would you like that?",
"name": "when",
"answers": [
{
"text": "Immediately"
},
{
"text": "10 minutes"
},
{
"text": "Half-an-hour"
}
]
},
{
"qtype": "text",
"text": "Anything else with that?",
"name": "anythingelse"
}
]
}
]
}
我想获取所有具有pagetype=“问题”的页面。我目前的做法如下:
BsonDocument profileDocument= profilesCollection.FindOneByIdAs<MongoDB.Bson.BsonDocument>(binaryId);
BsonElement pagesElement = profileDocument.GetElement("pages");
BsonArray pages=profileDocument.GetElement("pages").Value.AsBsonArray;
foreach (BsonValue pageV in pages.Values)
{
BsonDocument page = pageV.AsBsonDocument;
if (page["pagetype"].AsString == "question")
{
sb.Append("<br />Question Page:" + page.ToJson());
}
}
BsonDocument profileDocument=profilescolection.FindOneByIdAs(二进制ID);
BsonElement pagesElement=profileDocument.GetElement(“页面”);
BsonArray pages=profileDocument.GetElement(“pages”).Value.AsBsonArray;
foreach(在pages.Values中的BsonValue pageV)
{
BsonDocument page=pageV.AsBsonDocument;
如果(第[“页面类型”].AsString==“问题”)
{
sb.Append(“
问题页面:“+Page.ToJson());
}
}
代码似乎有点冗长和复杂——我只是想知道是否有更好的方法来实现这一点?谢谢假设profilesCollection的数据类型是MongoCollection,您可以缩短代码,如下所示:
var profileDocument = profilesCollection.FindOneById(binaryId);
foreach (BsonDocument page in profileDocument["pages"].AsBsonArray) {
if (page["pagetype"].AsString == "question") {
sb.Append("<br />Question Page:" + page.ToJson());
}
}
var profileDocument=profilescolection.FindOneById(binaryId);
foreach(profileDocument[“pages”].AsBsonArray中的b文档页){
如果(第[“页面类型”].AsString==“问题”){
sb.Append(“
问题页面:“+Page.ToJson());
}
}
谢谢您的改进。我真的希望有某种方法可以对内存中的对象执行查询,使用profileDocument[“pages”].Filter({pagetype:“question”})等语法,但看起来没有。无论如何,谢谢。