这是我的架构
{
"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
的文档小于notify
。我怎样才能实现这个目标?
我尝试过这样
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"}}}]);
关于node.js - 我在使用 `$unwind` 时获取了数组的分隔文档。如何将它们作为数组获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38475729/