如何使用MongoDB和C#驱动程序查询子文档集合

时间:2012-05-06 03:16:50

标签: mongodb mongodb-.net-driver 10gen-csharp-driver mongodb-query

我有以下结构:

public class ThreadDocument
{
    public ThreadDocument()
    {
        Messages = new List<Message>();
        Recipients = new List<Recipient>();
    }

    [JsonIgnore]
    public ObjectId Id { get; set; }
    public IList<Recipient> Recipients { get; set; }
    public IList<Message> Messages { get; set; }
    public DateTime LastMessageSent { get; set; }
    public string LastSentByUserName { get; set; }
    public string LastSentAvatarUrl { get; set; }
    public string Snippet { get; set; }
    public int MessageCount { get; set; }

}

public class Recipient
{
    public string UserId { get; set; }
    public int Status { get; set; }
}

public class Message
{
    public string FromUserId { get; set; }
    public string FromUsername { get; set; }
    public string FromAvatarUrl { get; set; }
    public DateTime Sent { get; set; }
    public string Text { get; set; }
}

当我保存时,它产生类似这样的东西:

{
  "_id" : ObjectId("4fa5eab4bfeddf23fcd01e4a"),
  "Recipients" : [{
      "UserId" : "4fa5d4d8bfeddf23fc72e590",
      "Status" : 1
    }, {
      "UserId" : "4fa5d4f9bfeddf23fc72e592",
      "Status" : 0
    }],
  "Messages" : [{
      "FromUserId" : "4fa5d4d8bfeddf23fc72e590",
      "FromUsername" : "a",
      "FromAvatarUrl" : null,
      "Sent" : ISODate("2012-05-06T03:06:28.396Z"),
      "Text" : "b"
    }],
  "LastMessageSent" : ISODate("2012-05-06T03:06:28.395Z"),
  "LastSentByUserName" : "a",
  "LastSentAvatarUrl" : null,
  "Snippet" : "b",
  "MessageCount" : 1
}

我想要做的是,如果已经创建了一个线程,使用相同的线程并根据用户是否发送给同一用户来反馈消息,反之亦然。

我认为这样的东西会起作用,但它返回null(没有值):

var thread = threadHelper.Collection.Find(
    Query.And(Query.EQ("Recipients.UserId", user.Id), Query.EQ("Recipients.UserId", sendToUser.Id))
).SingleOrDefault();

我想是一个包含所有的东西?还是全部?不确定如何进行查询。

1 个答案:

答案 0 :(得分:11)

尝试 ElemMatch

var thread = threadHelper.Collection.Find(
    Query.And(
        Query.ElemMatch("Recipients", Query.EQ("UserId", user.Id)), 
        Query.ElemMatch("Recipients", Query.EQ("UserId", sendToUser.Id))
    )
).SingleOrDefault();