代码之家  ›  专栏  ›  技术社区  ›  Woppi

如何在mongodb中查找正在分组的聚合集合?

  •  1
  • Woppi  · 技术社区  · 6 年前

    由于某些原因,我无法从聚合查询的另一个集合中检索作者名称。

    db.getCollection('books').aggregate([
    {
      $match: {
      authorId: { $nin: [ObjectId('5b9a008575c50f1e6b02b27b'), ObjectId('5ba0fb3275c50f1e6b02b2f5'), ObjectId('5bc058b6ae9a2a4d6df330b1')]},
      isBorrowed: { $in: [null, false] },
      status: 'ACTIVE',
    },
    },
    {
        $lookup: {
         from: "authors",
         localField: "authorId", // key of author id in "books" collection
         foreignField: "_id", // key of author id in "authors" collection
         as: "bookAuthor",   
        }
    },
    {
      $group: {
        _id: {
            author: '$authorId',    
        },
        totalSalePrice: {
          $sum: '$sale.amount',
        },
      },
    },
    {
      $project: {
          author: '$_id.author',
          totalSalePrice: '$totalSalePrice',    
          authorName: '$bookAuthor.name', // I can't make this appear  
          _id: 0,
      },
    },
    { $sort: { totalSalePrice: -1 } },
    

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    事实上,你已经失去了信心 bookAuthor $group 阶段你必须使用 $first 我想在下个月拿到它 $project 阶段

    { "$group": {
      "_id": { "author": "$authorId" },
      "totalSalePrice": { "$sum": "$sale.amount" },
      "authorName": { "$first": "$bookAuthor" }
    }},
    { "$project": {
      "author": "$_id.author",
      "totalSalePrice": "$totalSalePrice",    
      "authorName": { "$arrayElemAt": ["$bookAuthor.name", 0] }
      "_id": 0,
    }}
    
        2
  •  1
  •   mickl    6 年前

    这里缺少两件事:你需要 $unwind 转化 bookAuthor $group

    db.getCollection('books').aggregate([
        {
        $match: {
            authorId: { $nin: [ObjectId('5b9a008575c50f1e6b02b27b'), ObjectId('5ba0fb3275c50f1e6b02b2f5'), ObjectId('5bc058b6ae9a2a4d6df330b1')]},
            isBorrowed: { $in: [null, false] },
            status: 'ACTIVE',
            },
        },
        {
            $lookup: {
                from: "authors",
                localField: "authorId", 
                foreignField: "_id", 
                as: "bookAuthor", // this will be an array   
            }
        },
        {
            $unwind: "$bookAuthor"
        },
        {
            $group: {
                _id: {
                    author: '$authorId',    
                },
                bookAuthor: { $first: "$bookAuthor" },
                totalSalePrice: {
                    $sum: '$sale.amount',
                },
            },
        },
        {
            $project: {
                author: '$_id.author',
                totalSalePrice: '$totalSalePrice',    
                authorName: '$bookAuthor.name',  
                _id: 0,
            },
        },
        { $sort: { totalSalePrice: -1 } },
    ])