V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wuwukai007
V2EX  ›  Python

mongo aggregate 如何只返回数组中符合指定正则的某个元素?

  •  
  •   wuwukai007 · 2021-07-11 21:21:50 +08:00 · 1294 次点击
    这是一个创建于 991 天前的主题,其中的信息可能已经有所发展或是发生改变。

    表结构

     {
           data_list : ['2:333','3:222','xxx'],
           sid: '1111111111111'
     }
    

    要求返回 data_list 中符合指定正则的元素 /2:/

     {
         sid:'1111111111111',
         data_list: ['2:333']
    }
    
    
    # 现在是用 find 可以做到,如果用 aggregate  怎么做呢?
    db.score.find(
        {sid:'1111111111111',data_list:/^2:/},
        {"data_list.$": 1, sid:1 }
        )
    
    4 条回复    2021-07-12 11:03:11 +08:00
    lithiumii
        1
    lithiumii  
       2021-07-11 21:30:07 +08:00 via Android
    先 unwind 再 match ?
    wuwukai007
        2
    wuwukai007  
    OP
       2021-07-11 21:36:16 +08:00
    @lithiumii unwind 试了下,可以做到,但是效率有点低。
    catinsides
        3
    catinsides  
       2021-07-11 23:43:34 +08:00
    不知道你用的什么版本,4.2 可以这样:
    db.test.aggregate([{
    $project: {
    data_list: {
    $filter: {
    input: '$data_list',
    as: 'd',
    cond: {
    $regexMatch: {
    input: '$$d',
    regex: /^2:/
    }
    }
    }
    }
    }
    }])
    wuwukai007
        4
    wuwukai007  
    OP
       2021-07-12 11:03:11 +08:00
    @catinsides 我昨天也搜到了$regerxMatch,但是服务器是 4.0.19 的版本的😭
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3238 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 14:21 · PVG 22:21 · LAX 07:21 · JFK 10:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.