G.Mounika G.Mounika - 4 months ago 11
Node.js Question

I'm getting separated documents of an array while using `$unwind`. How to get them as it is as arrays?

This is my schema

{
"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}
}
]
}


Now I need to query the whole document in which document the
stock
is lessthan
notify
. How can I achieve this?

I tried like this

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}}}]


I'm getting response individually, but I need the response as it is like schema I mean even if one document in the array matches the query it should return the main documents as it is without splitting into different documents. Is it possible to get like that?

Answer

To reverse the effects of $unwind, we may use the aggregation operator $push.

Hence try the below query,

 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"}}}]);