반응형
mongodbc# BSON 문서로 작업하는 방법
답을 찾느라 많은 시간을 보냈습니다이것은 PHP에서는 매우 쉽지만 C#(C#과 mongo가 처음이라...)로 정리할 수 없습니다. 저장된 문서의 모든 수준을 반복하려고 합니다.문서는 다음과 같습니다.
{
"_id": ObjectId("51f90101853bd88971ecdf27"),
"fields": [
{
"ID": ObjectId("51fd09498b080ee40c00514e"),
"NAME": "ID",
"TYPE": "Text"
},
{
"ID": ObjectId("51fd09a68b080ee40c0064db"),
"NAME": "Title",
"TYPE": "Text"
},
{
"ID": ObjectId("51fd09b28b080ee40c004d31"),
"NAME": "Start Date",
"TYPE": "Date"
},
{
"ID": ObjectId("51fd09c28b080ee40c007f2e"),
"NAME": "Long Description",
"TYPE": "Memo"
}
],
"name": "TODB",
"updated": "Wed Jul 31 2013 08:20:17 GMT-0400 (Eastern Daylight Time)"
}
"이름"과 "업데이트"에 액세스하는 데 문제가 없지만 "필드" 배열에 액세스하는 방법을 알 수 없습니다.
지금까지의 코드:
{
MongoServer mongo = MongoServer.Create();
mongo.Connect();
var db = mongo.GetDatabase("forms");
mongo.RequestStart(db);
var collection = db.GetCollection("forms");
var query = new QueryDocument("name",
"TODB");
mongo.Disconnect();
}
@foreach(BsonDocument item in collection.Find(query))
{
@item.GetElement("name").Value
@item.GetElement("_id").Value
}
다시 한 번, 이름과 _id에 액세스할 수 있습니다. 하위 문서 값은 없습니다.
도움을 주셔서 미리 감사드립니다!판독치를 파악한 후에, 저도 자료를 작성하고 싶습니다...
몇 가지 방법이 있지만 다음 중 하나가 있습니다.
// build some test data
BsonArray dataFields = new BsonArray { new BsonDocument {
{ "ID" , ObjectId.GenerateNewId()}, { "NAME", "ID"}, {"TYPE", "Text"} } };
BsonDocument nested = new BsonDocument {
{ "name", "John Doe" },
{ "fields", dataFields },
{ "address", new BsonDocument {
{ "street", "123 Main St." },
{ "city", "Madison" },
{ "state", "WI" },
{ "zip", 53711}
}
}
};
// grab the address from the document,
// subdocs as a BsonDocument
var address = nested["address"].AsBsonDocument;
Console.WriteLine(address["city"].AsString);
// or, jump straight to the value ...
Console.WriteLine(nested["address"]["city"].AsString);
// loop through the fields array
var allFields = nested["fields"].AsBsonArray ;
foreach (var fields in allFields)
{
// grab a few of the fields:
Console.WriteLine("Name: {0}, Type: {1}",
fields["NAME"].AsString, fields["TYPE"].AsString);
}
종종 문자열 인덱서를 사용할 수 있습니다.["name-of-property"]필드 및 하위 문서 필드를 이동합니다.그런 다음 사용합니다.AsXYZ필드 값을 위와 같이 특정 유형으로 캐스트하는 속성입니다.
언급URL : https://stackoverflow.com/questions/18068772/mongodb-c-sharp-how-to-work-with-bson-document
반응형
'programing' 카테고리의 다른 글
| 두 NS 날짜 사이의 빠른 날짜 (0) | 2023.07.07 |
|---|---|
| JSON.Net에 DateTime을 지정되지 않은 경우에도 Utc로 serialize하라고 할 수 있습니까? (0) | 2023.07.07 |
| '{}' 유형을 '기록' 유형에 할당할 수 없습니다. (0) | 2023.07.07 |
| ggplot gem_text 글꼴 크기 컨트롤 (0) | 2023.07.07 |
| Entity Framework 6에서 아래 SELECT 문에 NOLOCK 사용 안 함 (0) | 2023.07.07 |