在$ in内添加模式,并汇总

时间:2018-10-31 20:42:26

标签: python sql mongodb aggregate pymongo

我正在$in函数的aggregate内添加模式。

我知道存在值,但是我的查询没有为该模式返回任何值。

这是我的查询:

db.collection.aggregate([{"$unwind":"$tags"},
{'$match': 
{
'tags.tag.name': {
    "$in": ['AA', 'CS', '/Nie/i']},
'auditRun': 12345}},
{'$project': {
 'tags.tag.name':1,
  '_id': 0}},])

我得到了 AA CS 的结果,但没有得到 Nie 的任何信息。

我也希望得到一些结果,因为我有一堆以 Nie 开头的名字。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您可以使用$or运算符和$regex来分别查找需要进行正则表达式搜索的项目。不能将其合并为一个项目列表。

db.collection.aggregate([{
    "$unwind": "$tags"
},
{
    '$match': {
        $or: [
          {'tags.tag.name': {"$in": ['AA','CS']}},
          {'tags.tag.name': { $regex: 'Nie', $options: 'i'}}
        ],
      'auditRun': 12345
    }
},
{
    '$project': {
        'tags.tag.name': 1,
        '_id': 0
    }
},
])

还想提到,如果您只需要以 Nie开头的,则您的正则表达式应为^Nie