Home > Software engineering >  MongoDB .NET Driver - Use $in in the match stage
MongoDB .NET Driver - Use $in in the match stage

Time:07-19

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.

CodePudding user response:

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" } }                                 
            }
        }
    }
)
  • Related