【问题标题】:mongoDb via nodejs sum a filed in a collecrionmongoDb通过节点js对集合中的一个字段求​​和
【发布时间】:2018-09-01 15:10:50
【问题描述】:
{
    "_id" : ObjectId("5b844ee13e214434ac627efd"),
    "productName" : "milk",
    "amount" : 1,
    "totalPrice" : 123,
    "cartId" : "pp",
    "cartItemPic" : "danuna.png",
    "__v" : 0
}
{
    "_id" : ObjectId("5b844ee43e214434ac627efe"),
    "productName" : "chease",
    "amount" : 5,
    "totalPrice" : 240,
    "cartId" : "pp",
    "cartItemPic" : "chease.png",
    "__v" : 0
}
{
    "_id" : ObjectId("5b856c8f285a2554e0cbaced"),
    "productName" : "yugort",
    "amount" : 1,
    "totalPrice" : 7,
    "cartId" : "lala",
    "cartItemPic" : "yugortmulerMix.png",
    "__v" : 0
}

我如何求和 "cartId"=pp" 的 "totalPrice" -via 节点 js。

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

第 1 步

创建一个 nodejs 应用

npm init -y

第 2 步

添加mongodb依赖

npm install --save mongodb

第 3 步

创建索引文件

index.js

第 4 步(在 index.js 文件中)

const mongodb = require('mongodb')

mongodb.connect(dbUrl, function (err, db) {

    // Access to your collection
    const collection = db.collection('collectionName')

    collection.aggregate([
           {$match: { cartId: 'pp' }},
           {$group: { 
                     _id: null,
                     totalPrice: { $sum: '$totalPrice' }
           }}
     ], function(err, result) {
            // Your totalPrice will be in result object
       })
});

那里有很多关于 mongodb 的教程...只要搜索它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多