2

我需要从“followingList.username”中获取所有用户名并与帖子的用户名进行比较,如果有任何匹配项需要将该用户名添加到数组中。

Person Model
{
    "_id" : ObjectId("554f20f5c90d3c7ed42303e1"),
    "username" : "fatihyildizhan",
    "followingList" : [ 
        {
            "_id" : ObjectId("55505b6ca515860cbcf7901d"),
            "username" : "gumusluk",
            "avatar" : "avatar.png"
        },
        {
            "_id" : ObjectId("58505b6ca515860cbcf7901d"),
            "username" : "yalikavak",
            "avatar" : "avatar.png"
        },
        {
            "_id" : ObjectId("58305b6ca515860cbcf7901d"),
            "username" : "gumbet",
            "avatar" : "avatar.png"
        }
    ]
}

Post Model
{
    "_id" : ObjectId("554f2df2a388R4b425b89833"),
    "username" : "yalikavak",
    "category" : "Summer",
    "text" : "blue voyage with yacht"
},
{
    "_id" : ObjectId("554f2df2a388P4b425b89833"),
    "username" : "yalikavak",
    "category" : "Winter",
    "text" : "is coming ..."
},
{
    "_id" : ObjectId("554f2df2a388K4b425b89833"),
    "username" : "gumbet",
    "category" : "Fall",
    "text" : "there are many trees"
}

我尝试获取如下结果代码块,但无法弄清楚。

var filter = Builders<Post>.Filter.AnyEq("username", usernameList);
var result = collection.Find(filter).ToListAsync().Result;

你能帮我解决这个问题吗?谢谢。

4

1 回答 1

5

逻辑颠倒了,如果我正确理解您的用例,您需要的是一个$in查询:

var filter = Builders<Post>.Filter.In("username", usernameList);
var result = collection.Find(filter).ToListAsync().Result;

在您的情况下,username是一个简单的字段,您希望与候选人列表匹配。AnyEq用于从复杂对象的嵌入列表中检查是否至少有一个与标准匹配。这仍然可以转换为 MongoDB 中的简单查询,但需要“触及”需要更复杂语法的对象。

于 2015-05-11T12:17:26.973 回答