MongoDB如果其他集合中存在字段/引用,则从汇总中排除文档

问题描述 投票:1回答:1
const sellerSchema = Schema(
  {
    name: String,
    url:String
  }
const productSchema = Schema(
  {
    title: String,
    sellerUrl:String
  }

下面的查询将从所有产品返回唯一的sellerUrl

context.Product.aggregate([
        {
          $group: {
            _id: "$sellerUrl",
          }
        }
      ]);

但是我也想从汇总中排除已经保存的卖方。因此,如果url == sellerUrl汇总必须排除该卖方。请帮助我

mongodb mongoose aggregation-framework
1个回答
0
投票
您可以尝试以下查询:

db.product.aggregate([ { $group: { _id: "", /** group on no condition & push all unique `sellerUrl` to sellerUrls array */ sellerUrls: { $addToSet: "$sellerUrl" } } }, { $lookup: { from: "seller", let: { sellerUrls: "$sellerUrls" }, // creating local variable pipeline: [ { $group: { _id: "", urls: { $addToSet: "$url" } } }, /** group on no condition & push all unique `url` to urls array */ { $project: { _id: 0, uniqueAndNotInSellerColl: { $setDifference: [ "$$sellerUrls", "$urls" ] } } } // get difference between two arrays ], as: "data" // As we're grouping will always be one doc/element in an array } }, /** Create a new root doc from getting first element(though it will have only one) from `data` array */ { $replaceRoot: { newRoot: { $arrayElemAt: [ "$data", 0 ] } } } ])

Test: mongoplayground

© www.soinside.com 2019 - 2024. All rights reserved.