db.mdb.collection('product_master').find({'project_code':'usha-fos', 'product_details' : {$elemMatch:{'Division':'Electric Fans'}}})
.limit(1000,function(err,results){
if(!err){
//console.log("projection succeeded");
//console.log("its working");
//console.log(results);
if(results.length==0){
console.log("length is 0")
}
app.send(req,res,results);//this will send the appropriate data to my controller
}
else{
//console.log("it is throwing an error")
}
})
我的JSON格式数据如下:
{
"_id" : ObjectId("57df7f5ab7079b1ab4d8a7dc"),
"agency_code" : "v5global",
"client_code" : "USHA_FOS",
"project_code" : "usha-fos",
"product_details" : [
{
"Division" : "Anything",
"Category" : "Ceiling Fans",
"Subcategory1" : "CF - UNIVERSAL - SMART",
"Subcategory2" : "STELLA",
"SKU" : "1200MM STELLA WH CF",
"SKU_Code" : "111048511",
"Description" : "",
"is_active" : "true"
},
{
"Division" : "Electric Fans",
"Category" : "Ceiling Fans",
"Subcategory1" : "CF - ADMIRE - UNDER LIGHT",
"Subcategory2" : "FONTANA",
"SKU" : "1280MM FONTANA ORCHID GOLD IVORY CF",
"SKU_Code" : "111055447",
"Description" : "",
"is_active" : "true"
},
{
"Division" : "AC&R",
"Category" : "Ceiling Fans",
"Subcategory1" : "CF - ADMIRE - UNDER LIGHT",
"Subcategory2" : "FONTANA",
"SKU" : "1250MM FONTANA MAPLE ANTIQUE BRASS CF",
"SKU_Code" : "111055448",
"Description" : "",
"is_active" : "true"
},
{
"Division" : "Electric Fans",
"Category" : "Ceiling Fans",
"Subcategory1" : "CF - ADMIRE - UNDER LIGHT",
"Subcategory2" : "FONTANA",
"SKU" : "1230MM FONTANA LOTUS BLK CHROME CF",
"SKU_Code" : "111056414",
"Description" : "",
"is_active" : "true"
},
{
"Division" : "Home Comfort",
"Category" : "Ceiling Fans",
"Subcategory1" : "CF - ADMIRE - UNDER LIGHT",
"Subcategory2" : "FONTANA",
"SKU" : "1230MM FONTANA LOTUS STEEL CF",
"SKU_Code" : "111056430",
"Description" : "",
"is_active" : "true"
}
]}
/ *我想要分区为电风扇的数据但我得到的所有数据都与分区无关。 请帮帮我* / / 提前致谢。 /
答案 0 :(得分:0)
$elemmatch(query) 会返回数组中的所有行。
$elemMatch(projection) 在用作投影时仅返回所有匹配行的第一行。
您可以使用数组聚合运算符 $filter 轻松获取所有匹配的行。
在此方案中,将根据传递的crtieria过滤产品详细信息。
aggregate([{
$match: {
"project_code": 'usha-fos'
}
}, {
$project: {
"agency_code": 1,
"client_code": 1,
"project_code": 1,
"product_details": {
"$filter": {
"input": "$product_details",
"as": "result",
cond: {
$eq: ["$$result.Division", "Electric Fans"]
}
}
}
}
}])