推荐学习书目
› 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 · Jul 11, 2021 · 2095 views
    This topic created in 1912 days ago, the information mentioned may be changed or developed.

    表结构

     {
           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 replies  •  2021-07-12 11:03:11 +08:00
    lithiumii
        1
    lithiumii  
       Jul 11, 2021 via Android
    先 unwind 再 match ?
    wuwukai007
        2
    wuwukai007  
    OP
       Jul 11, 2021
    @lithiumii unwind 试了下,可以做到,但是效率有点低。
    catinsides
        3
    catinsides  
       Jul 11, 2021
    不知道你用的什么版本,4.2 可以这样:
    db.test.aggregate([{
    $project: {
    data_list: {
    $filter: {
    input: '$data_list',
    as: 'd',
    cond: {
    $regexMatch: {
    input: '$$d',
    regex: /^2:/
    }
    }
    }
    }
    }
    }])
    wuwukai007
        4
    wuwukai007  
    OP
       Jul 12, 2021
    @catinsides 我昨天也搜到了$regerxMatch,但是服务器是 4.0.19 的版本的😭
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2889 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 00:04 · PVG 08:04 · LAX 17:04 · JFK 20:04
    ♥ Do have faith in what you're doing.