How to write match condition for array values?(如何为数组值编写匹配条件?)
问题描述
我已将值存储在多个变量中.下面是输入变量.
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.
在 userid 字段中,我们仅存储了Objectid"值.所以我关心的是如何将Objectid"添加到disuid"变量以及如何使用 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?
推荐答案
好的,有两种方法:
就像你一样:
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 }}]}}])
或者以我不喜欢的其他方式,因为与数据库中所有文档的 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
这篇关于如何为数组值编写匹配条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为数组值编写匹配条件?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
