在使用`$ unwind`的时候,我得到了一个数组的文档。 如何让它们像数组一样?

这是我的模式

{ "productid": {type: mongoose.Schema.Types.ObjectId, ref: 'products', required: true}, "itemcode": {type: String, required: true}, "itemname": {type: String, required: true/*, index: "text"*/}, "itemdescription": {type: String, required: true}, "itemimgurl": {type: String, required: true}, "mainprice": {type: Number}, "offerprice": {type: Number, required: true}, "unit": {type: String, required: true}, "offertag": {type: String}, "itemprice":[ { "itemname" :{type: String, required: true}, "unit": {type: String, required: true}, "offerprice": {type: Number, required: true}, "mainprice": {type: Number}, "stock": {type: Number, required: true}, "notify": {type: Number, required: true}, "status": {type: Boolean, required: true}, "itemimgurl": {type: String}, "offertag": {type: String} } ] } 

现在我需要查询整个文档在哪个文档中stock是lessnotify 。 我怎样才能做到这一点?

我试过这样

 subproduct.aggregate( [ {$unwind: "$itemprice"}, {$project: {"productid": 1, "itemcode": 1, "itemname": 1, "itemdescription": 1, "itemimgurl": 1, "mainprice": 1, "offerprice": 1, "unit": 1, "offertag": 1, "itemprice":1, "diff": {$subtract: ["$itemprice.stock", "$itemprice.notify"]}}}, {"$match": {'diff': {'$lt': 0}}}] 

我得到的响应个别,但我需要的响应,因为它是像架构我的意思是即使数组中的一个文档匹配的查询,它应该返回主文档,因为它没有分裂成不同的文件。 是否有可能得到这样的?

为了逆转$unwind的效果,我们可以使用聚合操作符$push

因此请尝试下面的查询,

  subproduct.aggregate( {$unwind: "$itemprice"}, {$project: { "productid": 1, "itemcode": 1, "itemname": 1, "itemdescription": 1, "itemimgurl": 1, "mainprice": 1, "offerprice": 1, "unit": 1, "offertag": 1, "itemprice":1, "diff": {$subtract: ["$itemprice.stock", "$itemprice.notify"]}}}, {"$match": {'diff': {'$lt': 0}}}, {$group:{_id:"$_id", "productid":{"$first":"$productid"}, "itemcode": {"$first":"$itemcode"}, "itemname": {"$first":"$itemname"}, "itemdescription": {"$first":"$itemdescription"}, "itemimgurl": {"$first":"$itemimgurl"}, "mainprice": {"$first":"$mainprice"}, "offerprice": {"$first":"$offerprice"}, "unit": {"$first":"$unit"}, "offertag": {"$first":"$offertag"}, "itemprice":{$push:"$itemprice"}}}]); 

您不一定需要$unwind运算符,在投影中使用$filter运算符根据指定的条件返回itemprice数组的子集。

以下面的聚合stream水线为例:

 subproduct.aggregate([ { "$project": { "productid": 1, "itemcode": 1, "itemname": 1, "itemdescription": 1, "itemimgurl": 1, "mainprice": 1, "offerprice": 1, "unit": 1, "offertag": 1, "itemprice": { "$filter": { "input": "$itemprice", "as": "el", "cond": { "$lt": [ { "$subtract": ["$$el.stock", "$$el.notify"] }, 0 ] } } } } } ])