4

I have the following structure:

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.

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.

1 Answer 1

11

Try 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();
Sign up to request clarification or add additional context in comments.

1 Comment

Who would you do it with the new version of the MongoDB c# driver ? because I do not see where the Query class is in the new version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.