如何使用MongoDB的官方C#驱动程序检索所有嵌入的文档值?

时间:2011-03-02 17:59:29

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

鉴于以下类和示例文档,如何使用官方C#驱动程序从QuestionChlection中检索AnswerChoice中的_id是'4d6d336ae0f84c23bc1fae00'的AnswerChoice文档。谢谢。

public class Question
{
     [BsonId]
     public ObjectId QuestionId
     {get;set;}

     public string Question
     {get;set;}

     public List<AnswerChoice> AnswerChoices
     {get;set;}
}

public class AnswerChoice
{
     [BsonId]
     public ObjectId AnswerChoiceId
     {get;set;}

     public string Answer
     {get;set;}

     public int Order
     {get;set;}

}

//示例文档

{
  "_id": "4d6d3369e0f84c23bc1facf7",
  "Question": "Question 1",
  "AnswerChoices": [
    {
      "_id": "4d6d3369e0f84c23bc1facf2",
      "Answer": "Answer Choice A",
      "Order": 1
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf3",
      "Answer": "Answer Choice B",
      "Order": 2
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf4",
      "Answer": "Answer Choice C",
      "Order": 3
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf5",
      "Answer": "Answer Choice D",
      "Order": 4
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf6",
      "Answer": "Answer Choice E",
      "Order": 5
    }
}

//检索具有AnswerChoice且_id为“4d6d336ae0f84c23bc1fae00”的问题的代码

List<Question> list = new List<Question>();
MongoServer _server = MongoServer.Create("mongodb://localhost");
MongoDatabase _database = _server.GetDatabase("test");
var query = Query.And(Query.EQ("AnswerChoices._id", new ObjectId("4d6d336ae0f84c23bc1fae00")));
MongoCollection<Question> collection = _database.GetCollection<Question>("Question");
MongoCursor<Question> cursor = collection.Find(query);

foreach (var q in cursor)
{
    list.Add(q);
}

//如何检索_id为“4d6d336ae0f84c23bc1fae00”的AnswerChoice对象?????

2 个答案:

答案 0 :(得分:4)

您应该加载问题(如上面的代码所示)并使用linq或foreach来获取具有指定_id的答案项。所以代码看起来像:

List<Question> list = new List<Question>();
MongoServer _server = MongoServer.Create("mongodb://localhost");
MongoDatabase _database = _server.GetDatabase("test");
var query = Query.And(Query.EQ("AnswerChoices._id", new ObjectId("4d6d336ae0f84c23bc1fae00")));
MongoCollection<Question> collection = _database.GetCollection<Question>("Question");
MongoCursor<Question> cursor = collection.Find(query);

var id = new ObjectId("4d6d336ae0f84c23bc1fae00");
foreach (var q in cursor)
{
    var answerChoice = q.AnswerChoices.Single(x=> x.AnswerChoiceId == id);
    list.Add(q);
}

另外我建议使用FindOne方法代替Find(因为我认为你确定只有一个上面指定的_id的答案存在)。

答案 1 :(得分:4)

看起来您只需要子文档而不是整个文档。 Mongodb目前不支持此功能。在匹配时,将返回整个文档。您的查询与Filtering embedded documents in MongoDB类似。 此功能请求有一个开放的JIRA项目,您应该在http://jira.mongodb.org/browse/SERVER-828

上投票