skip to Main Content

I have two collections one is for posts (PostInfo) and one for users (UserInfo), I join two collections and I want to find the posts if the given userid is in AsUser.Friends :

var docs = await _dbContext.PostInfos.Aggregate()
                  .Lookup("UserInfo", "UserId", "UserId", "AsUser")
                  .Unwind("AsUser")
                  .Match(
                      new BsonDocument() {
                          { "$expr", new BsonDocument() {
                                  { "$in", new BsonArray(){ "$AsUser.Friends", BsonArray.Create(user.UserId) } }                                 
                              }
                          }
                      }
                  )
                  .As<PostInfo>()
                  .Project<PostInfo>(Builders<PostInfo>.Projection.Exclude("AsUser"))
                  .ToListAsync();

This is userinfo document :

{
        "_id" : ObjectId("62d64398772c29b212332ec2"),
        "UserId" : "18F1FDB9-E5DE-4116-9486-271FE6738785",
        "IsDeleted" : false,
        "UserName" : "kaveh",
        "Followers" : [],
        "Followings" : [],
        "Friends" : [ 
            "9e3163b9-1ae6-4652-9dc6-7898ab7b7a00", 
            "2B5F6867-E804-48AF-BED3-672EBD770D10"
        ],
}

I am having a problem working with the $in operator.

Update

Also, I think this would work too (from here):

db.inventory.find( { tags: { $eq: [ "A", "B" ] } } )

But I can’t convert this to C# format.

2

Answers


  1. The $in operator (logic) is incorrect, you should check whether the userId in the AsUser.Friends array as below:

    {
      $match: {
        $expr: {
          $in: [
            "9e3163b9-1ae6-4652-9dc6-7898ab7b7a00",  // UserId
            "$AsUser.Friends"
          ]
        }
      }
    }
    

    Sample Mongo Playground


    For MongoDB C# syntax,

    .Match(
        new BsonDocument() 
        {
            { 
                "$expr", new BsonDocument() 
                {
                    { "$in", new BsonArray() { user.UserId, "$AsUser.Friends" } }                                 
                }
            }
        }
    )
    
    Login or Signup to reply.
  2. $expr is only required if you are doing a much more complicated expressive query, performing transformations and applying functions – for example calculating the average of and array and performing a match against that.

    All you need is simple find syntax in Match – and in MongoDB shell: find({"asuser.friends":user.UserId})

    or in your case:

    Match( new BsonDocument( "AsUser.Friends",user.UserId))

    In MongoDB A match against an array will match either any element or a whole array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search