zoukankan      html  css  js  c++  java
  • mongodb查询两个字段做加减乘除操作

    mongodb查询两个字段做加减乘除操作

    2019年03月14日 17:26:27 luffy5459 阅读数 472

     版权声明:欢迎转载 https://blog.csdn.net/feinifi/article/details/88556337

    和使用关系型数据库一样,我们在使用mongodb的时候,我们希望有这样的操作,就是查询两个字段的乘积或者和,这就需要用到聚合查询了,聚合查询的语法大致如下:

    db.user.aggregate({$project:{}},{$match:{}})

    我们将需要返回的字段放在$project中,查询条件放在$match中,我们的user表,数据如下:

    > db.user.find()
    { "_id" : ObjectId("5c8a007e9630feb0ec945d82"), "id" : 1, "name" : 111, "price" : 129, "count" : 1, "total" : 129 }
    { "_id" : ObjectId("5c8a00909630feb0ec945d83"), "id" : 2, "name" : 112, "price" : 100, "count" : 5, "total" : 500 }
    { "_id" : ObjectId("5c8a00a79630feb0ec945d84"), "id" : 3, "name" : 113, "price" : 120, "count" : 4, "total" : 480 }
    { "_id" : ObjectId("5c8a00b89630feb0ec945d85"), "id" : 4, "name" : 114, "price" : 160, "count" : 3, "total" : 480 }
    { "_id" : ObjectId("5c8a00c49630feb0ec945d86"), "id" : 5, "name" : 115, "price" : 160, "count" : 2, "total" : 480 }

    这样,我们的要求是查询price*count的结果和total的结果做对比。

    > db.user.aggregate({$project:{_id:0,id:1,total:1,total2:{$multiply:["$price","$count"]}}})
    { "id" : 1, "total" : 129, "total2" : 129 }
    { "id" : 2, "total" : 500, "total2" : 500 }
    { "id" : 3, "total" : 480, "total2" : 480 }
    { "id" : 4, "total" : 480, "total2" : 480 }
    { "id" : 5, "total" : 480, "total2" : 320 }

    在这个查询中,我们使用了$multiply,另外,他需要一个数组做参数:["$price","$count"],数组中的变量就是user表中的字段,这里我们必须使用双引号将他们括起来"$price","$count",否则会报错。

    下面列出常用的加减乘除的操作:

    加法:$add
    减法:$subtract
    乘法:$multiply
    除法:$divide

    另外,还有一些操作,比如$concat是用来连接两个或者多个字符串的:

    这些操作,只能用在aggregate聚合操作中,如果用在普通的find查找中,会报错:Unsupported projection option,如下图所示:

  • 相关阅读:
    POJ 1401 Factorial
    POJ 2407 Relatives(欧拉函数)
    POJ 1730 Perfect Pth Powers(唯一分解定理)
    POJ 2262 Goldbach's Conjecture(Eratosthenes筛法)
    POJ 2551 Ones
    POJ 1163 The Triangle
    POJ 3356 AGTC
    POJ 2192 Zipper
    POJ 1080 Human Gene Functions
    POJ 1159 Palindrome(最长公共子序列)
  • 原文地址:https://www.cnblogs.com/grj001/p/12225074.html
Copyright © 2011-2022 走看看