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

请教一个 mongodb 查询的写法

  •  
  •   zxCoder · Mar 29, 2021 · 2348 views
    This topic created in 1897 days ago, the information mentioned may be changed or developed.

    文档的格式是

    {
    	from: "a#b",
        to: ["a#a","a#c","b#b","abc#b"]
    }
    

    现在我想查出所有 from 字段#后面的字符串也在 to 字段#后面中出现 的所有文档

    就比如

    db.col.find({$expr:{$in:["$from", "$to"]}})
    

    但是不是整个字段去 in 匹配,而是只取#后面的字符串进行比较

    3 replies    2021-03-31 15:32:28 +08:00
    stabc
        1
    stabc  
       Mar 29, 2021
    $in 后面可以跟 function 的,所以前面可以自定义 function 里加 RegExp.

    不过不建议这样设计数据库,既然#后面的字符串需要比对,为什么不独立出来呢,json 做这个很方便啊
    catinsides
        2
    catinsides  
       Mar 29, 2021
    用聚合 aggregation,$split,$project,$match
    haha88
        3
    haha88  
       Mar 31, 2021
    先截取,在匹配? db.test2.aggregate([

    {$project: {
    from:{$substr:['$from',{$indexOfCP:['$from','#']},{$strLenCP:'$from'}]},to:'$to'

    }},
    { $match: { $expr: { $anyElementTrue: { $map: { input: "$to", as: "item", in: { $ne: [-1, { $indexOfBytes: ["$$item", "$from"] }] } } } } } }

    ]);
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2646 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 15:44 · PVG 23:44 · LAX 08:44 · JFK 11:44
    ♥ Do have faith in what you're doing.