【问题标题】:How to query a sub document collection using MongoDB and C# driver如何使用 MongoDB 和 C# 驱动程序查询子文档集合
【发布时间】:2012-05-15 02:51:55
【问题描述】:

我有以下结构:

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();

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

【问题讨论】:

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


    【解决方案1】:

    试试 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();
    

    【讨论】:

    • 你会用新版本的 MongoDB c# 驱动程序来做什么?因为我没有看到新版本中Query类在哪里
    猜你喜欢
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2013-09-16
    • 2017-07-09
    • 2012-09-02
    • 2012-03-04
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多