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

编程入门 行业动态 更新时间:2024-10-28 14:24:25
本文介绍了如何使用 MongoDB 和 C# 驱动程序查询子文档集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下结构:

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; } }

当我保存时,它会产生如下内容:

when I save, it produces something like this:

{ "_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 }

我想要做的是,如果已经创建了一个线程,使用相同的线程并根据用户是否向同一用户发送消息或反之亦然,将消息附加到该线程.

What I would like to do is if there is already a thread created, to use the same one and tack on messages to that one based upon if the user is sending to the same user or vice versa.

我认为这样的事情会起作用,但它返回 null(无值):

I thought something like this would work, but it is returning null (no values):

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

我想像一个包含所有?还是全部?不太确定如何进行查询.

I'm thinking like a contains all? or has all? Not really sure how to make the query.

推荐答案

试试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# 驱动程序查询子文档集合

本文发布于:2023-11-22 20:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   驱动程序   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!