问题描述
我有一个如下的销售货款。我想使用mongo shell进行查询以查找价格超过20的产品详细信息。
[{
"Customer_Info":{
"Customer_Id": 1,"First_Name": "John","Last_Name": "Smith","Address": "Sydney","State": "Sydney","Postcode": "0920","Phone": "0143464663"
},"Order_Info": [
{
"Order_Id": 1,"Order_Date": "01-01-2020","Delivery_Date": "01-01-2020","Line_Info": [
{
"Line_Id": 1,"Line_Price": 100,"Line_Units_Added": 2,"Product_Info": {
"Product_Id": 300,"Product_Name": "Orange","Product_Description": "Fruit","Number_in_Stock": 50,"Product_Weight": 1,"Product_Cost": 300,"Product_in_Date": "01-01-2020","Product_Type": "Fruits","Farmer_Info": {
"Farmer_Id": 123,"Farmer_First_Name": "Drake","Farmer_Last_Name": "Levine","Farmer_Address": "Sydney","Farmer_State": "Sydney","Farmer_Post_Code": "1200"
}
}
},{
"Line_Id": 5,"Line_Price": 25,"Line_Units_Added": "1","Product_Info": {
"Product_Id": 305,"Product_Name": "Banana","Number_in_Stock": 100,"Product_Cost": 100,{
"Line_Id": 6,"Product_Name": "Jackfruit","Number_in_Stock": 20,"Product_Cost": 50,{
"Line_Id": 7,"Line_Price": 200,"Line_Units_Added": 1,"Product_Info": {
"Product_Id": 310,"Product_Name": "Dragon Fruit","Number_in_Stock": 10,"Product_Cost": 2,"Farmer_Post_Code": "1200"
}
}
}
]
},{
"Order_Id": 2,"Line_Info": [
{
"Line_Id": 2,"Product_Info": {
"Product_Id": 301,"Product_Name": "Mango","Product_Cost": 500,"Farmer_Post_Code": "1200"
}
}
}
]
}
]
},{
"Customer_Info":{
"Customer_Id": 2,"First_Name": "Popeye","Last_Name": "Sailorman","Phone": "123456"},"Order_Info": [
{
"Order_Id": 3,"Line_Info": [
{
"Line_Id": 3,"Line_Price": 50,"Line_Units_Added": 5,"Product_Info": {
"Product_Id": 500,"Product_Name": "Spinach","Product_Description": "vegetables","Number_in_Stock": 30,"Product_Weight": 1.5,"Product_Cost": 30,"Product_Type": "Veg","Farmer_Info": {
"Farmer_Id": "420","Farmer_First_Name": "Olive","Farmer_Last_Name": "Lewine","Farmer_Post_Code": "1200"
}
}
}
]
}
]
}]
要使用mongo shell查找大于20的产品名称和产品成本。我已经完成了以下操作:
db.sales.find( { "Order_Info.Line_Info.Product_Info.Product_Cost": { $gt: 20} },{"_id": 0,"Order_Info.Line_Info.Product_Info.Product_Name": 1,"Order_Info.Line_Info.Product_Info.Product_Cost": 1} ).pretty();
但是不幸的是,它仅返回第一个文档值。如何实现?
解决方法
您可以通过聚合来实现
-
$map
帮助处理数组中的每个元素 -
$filter
帮助使用条件和过滤器
Mongo脚本
[
{
$project: {
Order_Info: {
$map: {
input: "$Order_Info",in: {
$filter: {
input: "$$this.Line_Info",cond: {
$gt: [
"$$this.Product_Info.Product_Cost",30
]
}
}
}
}
}
}
}
]