推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
DoodleSit
V2EX  ›  MongoDB

求助, mongodb 一个语句怎么写呢

  •  
  •   DoodleSit · May 20, 2021 · 2580 views
    This topic created in 1821 days ago, the information mentioned may be changed or developed.
    
    [
    {name:'AL',groups:['A','B']},
    {name:'AL',groups:['A','C']},
    {name:'BL',groups:null}
    ]
    
    

    聚合查询,想查出 groups 不存在或者 groups 包含 B 的结果

    如下语句有问题(还是会查出包含‘C’的),帮看看,谢谢

    
    db.db_types.aggregate([
            {
                $match: {
                    "$or": [
                        {
                            "groups": 'B'
                        },
                        {
                            "groups": {
                                $exists: false
                            }
                        }
                    ]
             }
       ])
    
    
    4 replies    2021-05-21 14:46:22 +08:00
    xiongbiao
        1
    xiongbiao  
       May 20, 2021
    没有问题
    Vegetable
        2
    Vegetable  
       May 20, 2021
    唯一的问题时,null 是 exists 的
    dfourc
        3
    dfourc  
       May 21, 2021
    返回带 C 的,这不是很正常嘛
    ```json
    {
    $match: {
    "groups": {
    $ne: null
    }
    }
    ```
    xkeyideal
        4
    xkeyideal  
       May 21, 2021
    仅限给出的数据结构,将 groups 从数组变成 map,就可以不需要使用 mongodb 的 aggregate,有时候也需要照顾一下系统的性能,使用普通的查询即可,db.db_types.find({"groups.B": 1})
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2928 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 105ms · UTC 10:12 · PVG 18:12 · LAX 03:12 · JFK 06:12
    ♥ Do have faith in what you're doing.