Mongodb-数组查询


  • 註冊用戶

    1.$all

    如果需要对数组中的多个元素进行匹配查询,就要用到$all  如下创建一个包含三个元素的集合:

    >db.product.insert(
        {
            "_id":ObjectId("4b5d85546de654d8ee55462"),
           "productno":
            [    "2020110",
                 "2020111",
                 "2020112"
            ] 
        }
    )
    
    >db.product.insert(
        {
            "_id":ObjectId("4e3d85546de654d8ee55962"),
           "productno":
            [    "2020110",
                 "2020113",
                 "2020114"
            ] 
        }
    )
    >db.product.insert(
        {
            "_id":ObjectId("4e3u85546de654d8ee48862"),
           "productno":
            [    "2020115",
                 "2020111",
                 "2020110"
            ] 
        }
    )

    现在要找到既有 2020110又有2020111的文档

    >db.product.find({productno:{$all:["2020110","2020111"]}})
    {    
        "_id":ObjectId("4b5d85546de654d8ee55462"),
        "productno":
          [    "2020110",
               "2020111"
               "2020112"
        ]
    },
    {    
          "_id":ObjectId("4e3u85546de654d8ee48862") ,
          "productno":
            [
                ""2020115,
                "2020111",
                "2020110"
            ]
    }
    

    2.$slice

    此操作符可以返回某个键匹配数组元素的一个子集,指定数组的长度

    >db.sonum.findOne()
    {
        "_id":ObjectId("56de5e24et65ddf36r85"),
        sonumber:
            [
                "a01",
                "a02",
                "a03",
                "a04",
                "a05",
                "a06"
            ]
    }
    

    想要返回前5个订单号,可以如下操作

    >db.sonum.findOne({"_id":ObjectId("56de5e24et65ddf36r85"},{"sonumber""{"$slice":5}})
      {
        "_id":ObjectId("56de5e24et65ddf36r85"),
        "sonumber":
            [
                "a01",
                "a02",
                "a03",
                "a04",
                "a05"
            ]
    }
    

    $slice常与$push一起使用,限制数组的总长度,$slice -5说明数组的长度为5,如果再$push两个元素进行 $slice -5操作

    >db.sonum.update({"_id":ObjectId("56de5e24et65ddf36r85"},{"$push":{"sonumber":{"$each":["A07","A08"],"$slice":-5}}})  
    >db.sonum.findOne({"_id":ObjectId("56de5e24et65ddf36r85"},{"sonumber""{"$slice":-5}})
      {
        "_id":ObjectId("56de5e24et65ddf36r85"),
        "sonumber":
            [
                "a04",
                "a05",
                "a06",
                "a07",
                "a08"
            ]
    }
    

    返回最后的5个元素["a04","a05","a06","a07","a08"],如果是$slice:5,则返回["a01","a02","a03","a04","a05"]


登录后回复
 

与 萌阔论坛 的连接断开,我们正在尝试重连,请耐心等待