账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于MongoDB查询两两共同出现的情况?
    62
    0

    MongoDB中有一个collection--foo 其中有这么一个字段--品牌 是一个数组 可以保存多个品牌 如下所示

    "brands" : [ 
          "西门子", 
          "ABB", 
          "GE"
      ],
    

    现在想做这样的查询统计 不同品牌共同出现的情况 如我想知道提及西门子的时候同时还提及到了哪些其他品牌 共同出现的频率是怎样的

    西门子 ABB 10 # 西门子 和 ABB 共同出现了10次
    西门子 GE 20 # 西门子 和 GE 共同出现了20次
    

    我现在想到的办法是 如下所示

    原始记录:
        "brands" : [ 
              "西门子", 
              "ABB", 
              "GE"
          ],
    
    新增一个字段-- `brand_and_mentioned_brands`-- 保存互相提及的情况
    [
      {
        main_brand: 西门子 #主品牌
        mentioned_brands: [ABB,GE] # 提及品牌
      },
      {
        main_brand: ABB
        mentioned_brands: [西门子,GE]
      },
      {
        main_brand: GE
        mentioned_brands: [西门子,ABB]
      }
    ]      

    这样的话 可以通过下面的查询语句来进行查询

    {$unwind:"$brand_and_mentioned_brands"},
    {$unwind:"$brand_and_mentioned_brands.mentioned_brands"},
    {$group:{"_id":{main_brand:"$brand_and_mentioned_brands.main_brand",mentioned_brand:"$brand_and_mentioned_brands.mentioned_brands"},count:{$sum:1}}}
    

    不知除此之外 有没其他更好的方式?

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 虫吃棒 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部