【问题标题】:Mongodb Driver use $in with match()Mongodb 驱动使用 $in 和 match()
【发布时间】:2022-07-19 14:10:18
【问题描述】:

我有两个集合,一个用于帖子(PostInfo),一个用于用户(UserInfo),我加入了两个集合,如果给定的 useridAsUser 中,我想查找帖子.朋友

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

这是用户信息文件:

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

我在使用 $in 操作员时遇到问题。

更新

我也认为这适用于(来自here):

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

但我无法将其转换为 C# 格式。

【问题讨论】:

    标签: c# mongodb asp.net-core


    【解决方案1】:

    $in操作符(逻辑)不正确,请检查AsUser.Friends数组中的userId是否如下:

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

    Sample Mongo Playground


    对于 MongoDB C# 语法,

    .Match(
        new BsonDocument() 
        {
            { 
                "$expr", new BsonDocument() 
                {
                    { "$in", new BsonArray() { user.UserId, "$AsUser.Friends" } }                                 
                }
            }
        }
    )
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2022-01-03
      • 2013-12-26
      • 2015-06-26
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2019-02-11
      相关资源
      最近更新 更多