如何写匹配条件的数组值? [英] How to write match condition for array values?

查看:55
本文介绍了如何写匹配条件的数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将值存储在多个变量中.下面是输入变量.

I have stored values in multiple variables. below are the input variables.

uid = Objectid("5d518caed55bc00001d235c1")
disuid = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']

这些值是动态更改的.下面是我的代码:

These values are changed dynamically. and below is my code:

user_posts.aggregate([{
    "$match": {
        "$or": [{ "userid": uid }, {
            "userid": {
                "$eq":
                    disuid
            }
        }]
    }
},
{
    "$lookup": {
        "from": "user_profile",
        "localField": "userid",
        "foreignField": "_id",
        "as": "details"
    }
},
{ "$unwind": "$details" },
{
    "$sort": { "created_ts": -1 }
},
{
    "$project": {
        "userid": 1,
        "type": 1,
        "location": 1,
        "caption": 1
    }
}
])

在上面的代码中,我只获得了匹配的 uid 值,但是我还需要匹配到 disuid 的文档.

In the above code, I am getting matched uid values only but I need documents matched to disuid also.

用户ID 字段中,我们仅存储了对象ID"值. 所以我关心的是如何在"disuid"变量中添加"Objectid",以及如何使用userid字段为两个变量编写匹配条件?

In userid field, we have stored "Objectid" values only. So my concern is how to add "Objectid" to "disuid" variable and how to write match condition for both variables using userid field?

推荐答案

好的,您可以通过两种方式来做到这一点:

Ok you can do it in two ways :

您已经拥有了:

uid = Objectid("5d518caed55bc00001d235c1")
disuid = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']

您需要使用python代码将字符串列表转换为ObjectId的列表:

You need to convert your list of strings to list of ObjectId's using python code :

from bson.objectid import ObjectId


disuid = ['5d76b2c847c8d3000184a090', '5d7abb7a97a90b0001326010']
my_list = []


for i in disuid:
    my_list.append(ObjectId(i))

它看起来像这样: [ObjectId('5d76b2c847c8d3000184a090'),ObjectId('5d7abb7a97a90b0001326010')]

然后使用新列表my_list,您可以像这样进行查询:

then by using new list my_list, you can do query like this :

user_posts.aggregate([{"$match" : { "$or" : [{ "userid" : uid }, { "userid" : { "$in" : my_list }}]}}])

或者以我不喜欢的另一种方式,因为与DB中所有文档中userid字段的n个值相比,仅转换很少的代码会更容易,但万一您希望将其转换为使用数据库查询完成:

Or in the other way which I wouldn't prefer, as converting just few in code is easier compared to n num of values for userid field over all documents in DB, but just in case if you want it to be done using DB query :

user_posts.aggregate([{$addFields : {userStrings : {$toString: '$userid'}}},{"$match" : { "$or" : [{ "userid" : uid }, { "userStrings" : { "$in" : disuid }}]}}])

注意::如果您没有bson软件包,则需要通过执行pip install bson

Note : In case if you don't have bson package, then you need to install it by doing something like pip install bson

这篇关于如何写匹配条件的数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆