Count no.of elements in an array and sum for every document of a collection in mongodb? - mongodb

I need to count to number of all the products from all the orders and also number of products per individual order ?
data in my collection ( order_fact) :
{"orderid":"c3e15faf-e338-4ed5-9bbb-bbcd15295fd7","Id_cust":"10995116278711","Id_date":"91","TotalPrice":1933.53,"Orderline":[{"productId":"4165","asin":"B005G2G2SQ","title":"ESEE-6 Plain Black Blade With Grey Removable Lined Micarta Handles 1095 Carbon Steel 57-Rc","price":140.05,"brand":"Fila_(company)"},{"productId":"5916","asin":"B001CJ2LQ4","title":"Aimpoint M4s 2 Minute of Angle QRP2 CompM4 Sight with Mount","price":804.95,"brand":"Atletica"},{"productId":"7779","asin":"B003DO5L3G","title":"Lee Precision Load Master 223 Remington Reloading Rifle Kit (Red)","price":249.26,"brand":"BURRDA"},{"productId":"2722","asin":"B0017U1MJU","title":"Casio Mens PAW1500-1V Pathfinder Multi-Band Solar Atomic Ultimate Watch","price":190.27,"brand":"Reebok"},{"productId":"52","asin":"B007SYGLZO","title":"Armasight Spark CORE Multi-Purpose Night Vision Monocular","price":549.0,"brand":"Signia_(sportswear)"}],"Livreur":{"Id_livreur":"91bcee9f-8896-4e18-a24c-a8e86b97b3a1","Nom":"Tyson Anderson","gender":"Male","phone":"7-458-665-3444"}},
{"orderid":"35b26e6d-e450-4edc-9071-306cea10a083","Id_cust":"10995116278711","Id_date":"249","TotalPrice":1540.91,"Orderline":[{"productId":"1978","asin":"B001CZBMRC","title":"Benchmade Osborne Design Rift Knife","price":178.5,"brand":"CCM_(ice_hockey)"},{"productId":"857","asin":"B004IIKA2I","title":"Barnett Quad 400 Crossbow Package (Quiver 3 - 22-Inch Arrows and 4x32mm Scope)","price":354.99,"brand":"Fischer_(company)"},{"productId":"8362","asin":"B00635GTTW","title":"Schwinn IC2 Indoor Cycling Exercise Bike","price":422.49,"brand":"Admiral_Sportswear"},{"productId":"216","asin":"B000GKN45C","title":"Swagman XTC-4 Cross-Country 4-Bike Hitch Mount Rack (2-Inch Receiver Hitch)","price":349.99,"brand":"Elfin_Sports_Cars"},{"productId":"7766","asin":"B000KKEPJ2","title":"Lyman Reloading Press T-Mag Turret Press","price":234.94,"brand":"BURRDA"}],"Livreur":{"Id_livreur":"48d64c09-7a63-4fca-815a-a96921a82ee7","Nom":"Abdul Coll","gender":"Male","phone":"1-273-204-4721"}},
{"orderid":"ffaec62e-9875-42af-8789-0a97eabe77e4","Id_cust":"10995116278711","Id_date":"67","TotalPrice":1058.41,"Orderline":[{"productId":"2675","asin":"B00BPRM2O4","title":"Large Exercise Mat Large Workout Mat With A Unique Fabric Finish That Provides Excellent Traction And Floor Protection. Can Be Used In Conjunction With The Square36 YOGA Mat. The Square36 CARDIO Mat - The BIG Exercise Mat- Step Into the Square.","price":159.99,"brand":"Reebok"},{"productId":"1380","asin":"B000EQCVQ6","title":"Eureka! Apex 2XT Two-Person Tent","price":175.16,"brand":"Topper_(sports)"},{"productId":"9665","asin":"B004H4VSI8","title":"IRONMAN HIGH CAPACITY GRAVITY 3000 INVERSION TABLE","price":239.8,"brand":"Wilson_Sporting_Goods"},{"productId":"7603","asin":"B0017SC9H6","title":"Zero Tolerance Combat Folding Knife","price":199.0,"brand":"Tramontana_(sports_car)"},{"productId":"887","asin":"B00BCLL8C0","title":"SportRack SR7018 Vista XL Rear Opening Cargo Box 18-Cubic Feet","price":284.46,"brand":"Fischer_(company)"}],"Livreur":{"Id_livreur":"7548ac7b-5bf7-4c5a-a80d-5390b73b9b90","Nom":"Henry Wilde","gender":"Male","phone":"3-624-033-5243"}},
{"orderid":"125e7887-c41d-4a5a-aa6b-d2a3679d58e7","Id_cust":"10995116278711","Id_date":"477","TotalPrice":1624.98,"Orderline":[{"productId":"6250","asin":"B005DYQ9V2","title":"Invicta Men s 1463 Reserve Collection Chronograph Silver Dial Stainless Steel Watch","price":199.95,"brand":"Keuka_(brand)"},{"productId":"1138","asin":"B000AMRN12","title":"Stamina AeroPilates Reformer with Free-Form Cardio Rebounder","price":449.0,"brand":"Topper_(sports)"},{"productId":"7575","asin":"B005D7FXMA","title":"Cygolite Expilion 400 Usb Rechargeable Headlight with Quick Release Li-Ion Battery Stick and Wall Charger","price":113.99,"brand":"Derbi"},{"productId":"6529","asin":"B005Z2CYX4","title":"Zero Tolerance ZT0550 Hinderer Design Folding Knife","price":160.0,"brand":"CA_Sports"},{"productId":"7125","asin":"B007INYN6O","title":"Barnett Zombie 350 CRT Crossbow","price":702.04,"brand":"Elan_Snowboards"}],"Livreur":{"Id_livreur":"a1060a87-fdff-4acc-b728-c805b72b0740","Nom":"Percy Thornton","gender":"Male","phone":"5-744-522-0782"}},
{"orderid":"b259eafc-2f47-47dc-927b-5b6d6edbba1d","Id_cust":"10995116278711","Id_date":"617","TotalPrice":1484.76,"Orderline":[{"productId":"7667","asin":"B008W1TUAK","title":"MAGPUL ACS CARB STOCK MIL-SPEC BLACK","price":98.99,"brand":"POC_Sports"},{"productId":"6406","asin":"B001CJX50K","title":"Kinetic Rock n Roll Trainer w/Road Resistance Unit","price":389.99,"brand":"MYLAPS_Sports_Timing"},{"productId":"1883","asin":"B000O8Z7TW","title":"KNEX Education - Exploring Machines","price":126.79,"brand":"TRYMAX"},{"productId":"4158","asin":"B003AQKQAA","title":"Vortex Viper PST 6-24x50 Rifle PST-624S1-M","price":749.0,"brand":"Fila_(company)"},{"productId":"7578","asin":"B00D43A93I","title":"Under Armour Hammer 8600014-4808 Polarized Wrap Sunglasses","price":119.99,"brand":"Derbi"}],"Livreur":{"Id_livreur":"eb135eef-7ee2-4d90-b073-cbd4570935b3","Nom":"Violet Adler","gender":"Female","phone":"5-466-075-2676"}},
{"orderid":"b5755c1e-fc3f-4481-a175-edfc82290ea5","Id_cust":"10995116278711","Id_date":"208","TotalPrice":2487.71,"Orderline":[{"productId":"965","asin":"B000O3AVNY","title":"Advanced Elements AdvancedFrame Expedition Kayak","price":599.99,"brand":"Donnay_(sports)"},{"productId":"6888","asin":"B0029KL3S2","title":"Precor 240i Commercial Series StretchTrainer","price":704.2,"brand":"Elan_(company)"},{"productId":"6439","asin":"B004PJ1J4S","title":"Invicta Men s 6566 Subaqua Noma IV Collection Chronograph Black Polyurethane Watch","price":340.65,"brand":"MYLAPS_Sports_Timing"},{"productId":"9503","asin":"B0034PXYRY","title":"Eotech EXPS3-0 Holographic Weapon Site","price":606.92,"brand":"EA_Sports"},{"productId":"7740","asin":"B00271ERVI","title":"Crimson Trace Lasergrip for Ruger Lcr","price":235.95,"brand":"BURRDA"}],"Livreur":{"Id_livreur":"c75a672e-37cf-498e-8bf9-8dae7857165f","Nom":"Renee Eyres","gender":"Female","phone":"6-311-624-4031"}},
{"orderid":"8a129f4e-e736-4919-9a22-c98373f1df3b","Id_cust":"10995116278711","Id_date":"390","TotalPrice":1233.67,"Orderline":[{"productId":"1929","asin":"B004P4HH8U","title":"Barnett Ghost 350 CRT Crossbow Package (Quiver 3 - 20-Inch Arrows and Illuminated 3x32mm Scope)","price":509.99,"brand":"TRYMAX"},{"productId":"2940","asin":"B004IIZVQ8","title":"Barnett Wildcat C5 Crossbow Package (Quiver 3 - 20-Inch Arrows and Premium Red Dot Sight)","price":342.99,"brand":"Volkl"},{"productId":"3174","asin":"B006U0YZPA","title":"Bushnell X-8 6MP Trail Camera with Night Vision and Field Scan","price":136.94,"brand":"Daei_Sport"},{"productId":"6527","asin":"B003MA1SSI","title":"Sadlak Industries M14 National Match Spring Guide","price":40.75,"brand":"CA_Sports"},{"productId":"1759","asin":"B007L4ZGXE","title":"Zero Tolerance ZT0560 Hinderer Design Black Folding Knife","price":203.0,"brand":"Olympikus"}],"Livreur":{"Id_livreur":"2ccb39c1-5c1a-46d8-b394-fc887bd4cecd","Nom":"Faith Flanders","gender":"Female","phone":"2-586-775-3278"}},
{"orderid":"bb671476-5f67-414a-9b84-77498b05f0bd","Id_cust":"10995116278711","Id_date":"205","TotalPrice":1601.81,"Orderline":[{"productId":"810","asin":"B009K28INA","title":"Schwinn 425 Elliptical Trainer (2013)","price":599.99,"brand":"Fischer_(company)"},{"productId":"6802","asin":"B000WY8ZHO","title":"Luminox Men s Navy Seal ColorMark Watch 3051","price":229.09,"brand":"Onda_(sportswear)"},{"productId":"3178","asin":"B007O5B0LC","title":"Weslo Cadence G 5.9 Treadmill","price":351.0,"brand":"Daei_Sport"},{"productId":"2126","asin":"B0025YCYK8","title":"Spyderco Temperence 2 Canvas Micarta Plain Edge Knife","price":207.72,"brand":"Li-Ning"},{"productId":"6736","asin":"B002QWB8HY","title":"CamelBak BFM 3L Backpack","price":214.01,"brand":"Onda_(sportswear)"}],"Livreur":{"Id_livreur":"629b2edd-8bd4-4d50-8e63-33f4904ffd2c","Nom":"Stephanie Garcia","gender":"Female","phone":"6-618-288-6820"}},
{"orderid":"d3016947-f478-4782-941d-37132482a10a","Id_cust":"10995116278711","Id_date":"694","TotalPrice":1534.78,"Orderline":[{"productId":"3029","asin":"B00AJK9CW8","title":"Seiko Men s SRP307 Classic Automatic Dive Watch","price":192.87,"brand":"Kettler"},{"productId":"2964","asin":"B004V956P0","title":"Crosman Optimus Break Barrel Air Rifle (.177)","price":91.98,"brand":"Volkl"},{"productId":"4115","asin":"B003UNZHNY","title":"Schwinn A10 Upright Exercise Bike (2011)","price":199.99,"brand":"Fila_(company)"},{"productId":"6853","asin":"B0081MPIBA","title":"ETEK4 - Planet Eclipse Etek 4 LT / AM Paintball Guns","price":499.95,"brand":"Elan_(company)"},{"productId":"893","asin":"B001AS697O","title":"Bowflex PR1000 Home Gym","price":549.99,"brand":"Fischer_(company)"}],"Livreur":{"Id_livreur":"787192a7-8417-44a9-a5bb-dd9060afd524","Nom":"Isla Denton","gender":"Female","phone":"1-260-416-8800"}},
{"orderid":"30dd4a79-4dac-4043-8fbc-e746e78aced3","Id_cust":"10995116278711","Id_date":"702","TotalPrice":1329.04,"Orderline":[{"productId":"2726","asin":"B005SSWKMK","title":"Casio Men s PRW2500T-7CR Pathfinder Triple Sensor Tough Solar Digital Multi-Function Titanium Pathfinder Casual Watch","price":266.12,"brand":"Reebok"},{"productId":"6563","asin":"B0014NDXGA","title":"Bushnell Tour V2 Standard Edition Golf Laser Rangefinder","price":290.06,"brand":"Onda_(sportswear)"},{"productId":"4856","asin":"B001QD48GC","title":"FreeForm Hideaway Home Gym","price":641.93,"brand":"ASICS"},{"productId":"7653","asin":"B007ZNUG9K","title":"Blackhawk Black TraverseTrack Bipod - 10 - BH71BP10BK","price":50.98,"brand":"POC_Sports"},{"productId":"4166","asin":"B00AJT98OQ","title":"Universal Brass Catcher","price":79.95,"brand":"Fila_(company)"}],"Livreur":{"Id_livreur":"5acb6f8a-fb71-4b32-b40d-fde782d70600","Nom":"Belinda Marshall","gender":"Female","phone":"6-671-643-4273"}},
I need two queries, the first :
Number of all the products from all the orders
the second query :
Number of all the products from per order

You can have something like this :
For First Question :
db.getCollection('order_fact').aggregate([{
$group: {
_id: '',
allProductsFromAllOrdersCount: { $sum: { $cond: { if: { $isArray: "$Orderline" }, then: { $size: "$Orderline" }, else: "NA"} } }
}
}, {
$project: {
_id: 0,
allProductsFromAllOrdersCount: 1
}
}])
For Second Question :
If OrderLine is Array for sure :
db.getCollection('order_fact').aggregate([{$project : {orderid:1 ,OrderLine : 1, totalNoOfProducts : { $size: "$Orderline"}}}])
else with conditional statements:
db.getCollection('order_fact').aggregate([{$project : {orderid:1 ,OrderLine : 1, totalNoOfProducts : { $cond: { if: { $isArray: "$Orderline" }, then: { $size: "$Orderline" }, else: "NA"} }}}])
If you need the count along with original document to be returned :
db.getCollection('order_fact').aggregate([{$addFields: {totalNoOfProducts : { $cond: { if: { $isArray: "$Orderline" }, then: { $size: "$Orderline" }, else: "NA"} }}}])

Related

I want to search through <dynamic> List in dart

I have a list of products, the list is below:
List<dynamic>products = [
{
"id": 3,
"name": "Apple MacBook Air 13.3-Inch 10th Gen Core i3-1.1GHz, 8GB RAM, 256GB SSD (MWTJ2) Space Gray 2020",
"price": 126000,
"descriptions": "Processor\tIntel Core i3-1000NG4 Processor (4M Cache, 1.10 GHz up to 3.20 GHz)\r\n\r\nMemory\t 8GB 3733MHz LPDDR4X onboard RAM\r\n\r\nStorage\t 256GB SSD\r\nGraphics\tIntel Iris Plus Graphics; **Support for Thunderbolt 3–enabled external graphics processors (eGPUs)\r\n\r\nDisplay\t 13.3-inch (diagonal) Retina LED-backlit display with IPS technology; 2560-by-1600 native resolution at 227 pixels per inch with support for millions of colors\r\n\r\nAdapter\t 30W USB-C Power Adapter; USB-C power port\r\n\r\nBattery\tUp to 10 hours battery back (Video & web browsing up to 05 hours depending on resolution) Built-in 49.9 watt-hours lithium-polymer battery\r\n\r\nOperating System\tmacOS\r\n\r\nNetworking\t 802.11ac Wi-Fi wireless networking; IEEE 802.11a/b/g/n compatible\r\n\r\nTouchpad\t Multi-Touch gestures\r\n\r\nKeyboard\tBacklit Keyboard - US English Retina is equipped with: 78 keys (ANSI specification) or 79 keys (ISO specification), including 12 function keys and 4 direction keys arranged in an \"inverted T\" shape. Ambient light sensor Force touchpad brings precise cursors Control and pressure-sensing functions, support forceful long-press, acceleration function, pressure-sensitive drawing, and multi-touch gestures\r\n\r\nBluetooth\tBluetooth 5.0 wireless technology\r\n\r\nAudio\t Stereo speakers; Wide stereo sound; Support for Dolby Atmos playback; Three-mic array with directional beamforming; 3.5 mm headphone jack\r\n\r\nOptical Drive None\r\n\r\nSoftware\tFinal Cut Pro X; Logic Pro X\r\n\r\nWebCam\t720p FaceTime HD camera\r\n\r\nFingerprint\tYes\r\n\r\nDisplay Touch\tDisplay WithTouch ID sensor\r\n\r\nPorts & Connectors\t2 x Thunderbolt 3 (Supports DisplayPort and Power Delivery); Thunderbolt (up to 40Gb / s); USB 3.1 Gen 2 (up to 10Gb / s; 1 x HDMI; 1 x VGA; 1 x 3.5 mm Headphone Output\r\n\r\nColor\tSpace Gray\r\n\r\nDimensions (W x D x H)\tThickness: 0.41 to 1.61 cm (0.16 to 0.63 inches); Width: 30.41 cm (11.97 inches); Depth: 21.24 cm (8.36 inches)\r\n\r\nWeight\t1.29 kg (2.8 lbs)\r\n\r\nIncluded in the Box\tMacBook Air; 30W USB-C Power Adapter; USB-C Charge Cable (2 m)\r\n\r\nWarranty \t01 year International Limited Warranty (Terms & Condition Apply As Per Apple)",
"image": "/images/macbook_IU3NvNF.jpg",
"created_at": "2022-08-19T17:42:13.118095Z",
"updated_at": "2022-08-19T17:42:13.118095Z",
"stock": true,
"category": 1,
"user": "mosta"
},
{
"id": 2,
"name": "MSI Modern 14 B10MW Core i3 10th Gen 14\" Full HD Laptop",
"price": 50890,
"descriptions": "Processor Intel Core i3 10110U Processor (4MB Cache, 2.1Ghz up to 4.1Ghz)\r\n\r\nDisplay 14.0\" FHD (1920x1080), IPS-Level Display\r\n\r\nMemory 4GB 2666MHz DDR4 RAM, (Suppoorted Up to 16GB)\r\n\r\nStorage 256GB NVMe SSD (Supported Up to 1TB)\r\n\r\nGraphics Intel UHD Graphics\r\n\r\nOperating System Free Dos\r\nBattery 39.3Whr\r\n\r\nAdapter 65W adapter\r\n\r\nInput Devices\r\nKeyboard Backlight Keyboard\r\n\r\nWebCam HD type (30fps#720p)\r\nCard Reader 1x Micro SD\r\n\r\nNetwork & Wireless Connectivity\r\nWi-Fi 802.11 ac Wi-Fi\r\n\r\nBluetooth Bluetooth v5\r\n\r\nPorts, Connectors & Slots\r\nUSB (s) 2x Type-A USB2.0\r\n\r\n1x Type-C USB3.2 Gen2\r\n\r\nHDMI 1x (4K # 30Hz) HDMI\r\n\r\nAudio Jack Combo 1x Mic-in/Headphone-out Combo Jack\r\n\r\nExtra RAM Slot NO\r\n\r\nExtra M.2 Slot NO\r\n\r\nPhysical Specification\r\nDimensions (W x D x H) 319 x 220.2 x 16.9 mm\r\n\r\nWeight 1.3 kg\r\n\r\nColor(s) Carbon Gray\r\n\r\nWarranty\r\nManufacturing Warranty 02 Year",
"image": "/images/msi_sCwzOcI.jpeg",
"created_at": "2022-08-19T17:41:53.358014Z",
"updated_at": "2022-08-19T17:41:53.358014Z",
"stock": true,
"category": 1,
"user": "mosta"
},
{
"id": 1,
"name": "iPhone 13 Pro Max",
"price": 169000,
"descriptions": "First Release\tSeptember 24, 2021\r\n\r\nColors\tGraphite, Gold, Silver, Sierra Blue\r\n\r\nNetwork\t2G, 3G, 4G, 5G\r\n\r\nSIM\tNano / Electronic SIM\r\n\r\nWLAN\t✅ dual-band, Wi-Fi hotspot\r\n\r\nBluetooth\t✅ v5.0, A2DP, LE\r\n\r\nGPS\t✅ A-GPS, GLONASS, GALILEO, BDS, QZSS\r\n\r\nRadio\t✖\r\n\r\nUSB\tLightning, USB 2.0\r\n\r\nOTG\t✅\r\n\r\nUSB Type-C\t✖ (Proprietary reversible connector)\r\n\r\nNFC\t✅\r\n\r\nStyle\tNotch\r\n\r\nMaterial\t Gorilla Glass front & back, stainless steel frame\r\n\r\nWater Resistance\t✅ IP68 dust/water resistant (up to 6m for 30 mins)\r\n\r\nDimensions\t160.8 x 78.1 x 7.7 mmillimeters\r\n\r\nWeight\t240 grams\r\n\r\nSize\t6.7 inches\r\n\r\nResolution\t1284 x 2778 pixels (458 ppi)\r\n\r\nTechnology\tSuper Retina XDR OLED Touchscreen\r\n\r\nProtection\t✅ Scratch-resistant ceramic glass, oleophobic coating\r\n\r\nFeatures\tDolby Vision, HDR10, 1200 nits (max.), 120Hz, true-tone, wide color gamut\r\n\r\nResolution\tQuad 12+12+12 Megapixel + TOF 3D LiDAR scanner\r\n\r\nFeatures\tDual Pixel PDAF, sensor-shift OIS, dual-LED flash, ultrawide, depth, telephoto, 3x optical zoom & more\r\n\r\nVideo Recording\t4K (2160p), Dolby Vision HDR, ProRes, Cinematic mode, stereo sound rec.\r\n\r\nResolution\tDual 12 Megapixel + SL 3D\r\n\r\nFeatures\tF/2.2, HDR, 1/3.6″, depth / biometrics sensor\r\n\r\nVideo Recording\t4K (2160p), gyro-EIS\r\n\r\nType and Capacity\tLithium-ion 4352 mAh (non-removable)\r\n\r\nFast Charging\t✅ 27W Fast Charging (50% in 30 minutes)\r\n\r\nUSB Power Delivery 2.0\r\n\r\nWireless Charging\t✅ Fast Wireless Charging (15W MagSafe, 7.5W Qi magnetic)\r\n\r\nOperating System\tiOS 15\r\n\r\nChipset\tApple A15 Bionic (5 nm)\r\n\r\nRAM\t6 GB\r\n\r\nProcessor\tHexa-core, up to 3.22 GHz\r\n\r\nGPU\tApple GPU (5-core graphics)",
"image": "/images/iPhone13promax_YiZ3ktK.jpg",
"created_at": "2022-08-19T17:41:27.837767Z",
"updated_at": "2022-08-19T17:41:27.837767Z",
"stock": true,
"category": 2,
"user": "mosta"
}
]
I want to search through the above list by product name. And also want a make separate list contain one single map.
If i search "apple" the result should be:
List<dynamic> searchResult = [
{
"id": 3,
"name": "Apple MacBook Air 13.3-Inch 10th Gen Core i3-1.1GHz, 8GB RAM, 256GB SSD (MWTJ2) Space Gray 2020",
"price": 126000,
"descriptions": "Processor\tIntel Core i3-1000NG4 Processor (4M Cache, 1.10 GHz up to 3.20 GHz)\r\n\r\nMemory\t 8GB 3733MHz LPDDR4X onboard RAM\r\n\r\nStorage\t 256GB SSD\r\nGraphics\tIntel Iris Plus Graphics; **Support for Thunderbolt 3–enabled external graphics processors (eGPUs)\r\n\r\nDisplay\t 13.3-inch (diagonal) Retina LED-backlit display with IPS technology; 2560-by-1600 native resolution at 227 pixels per inch with support for millions of colors\r\n\r\nAdapter\t 30W USB-C Power Adapter; USB-C power port\r\n\r\nBattery\tUp to 10 hours battery back (Video & web browsing up to 05 hours depending on resolution) Built-in 49.9 watt-hours lithium-polymer battery\r\n\r\nOperating System\tmacOS\r\n\r\nNetworking\t 802.11ac Wi-Fi wireless networking; IEEE 802.11a/b/g/n compatible\r\n\r\nTouchpad\t Multi-Touch gestures\r\n\r\nKeyboard\tBacklit Keyboard - US English Retina is equipped with: 78 keys (ANSI specification) or 79 keys (ISO specification), including 12 function keys and 4 direction keys arranged in an \"inverted T\" shape. Ambient light sensor Force touchpad brings precise cursors Control and pressure-sensing functions, support forceful long-press, acceleration function, pressure-sensitive drawing, and multi-touch gestures\r\n\r\nBluetooth\tBluetooth 5.0 wireless technology\r\n\r\nAudio\t Stereo speakers; Wide stereo sound; Support for Dolby Atmos playback; Three-mic array with directional beamforming; 3.5 mm headphone jack\r\n\r\nOptical Drive None\r\n\r\nSoftware\tFinal Cut Pro X; Logic Pro X\r\n\r\nWebCam\t720p FaceTime HD camera\r\n\r\nFingerprint\tYes\r\n\r\nDisplay Touch\tDisplay WithTouch ID sensor\r\n\r\nPorts & Connectors\t2 x Thunderbolt 3 (Supports DisplayPort and Power Delivery); Thunderbolt (up to 40Gb / s); USB 3.1 Gen 2 (up to 10Gb / s; 1 x HDMI; 1 x VGA; 1 x 3.5 mm Headphone Output\r\n\r\nColor\tSpace Gray\r\n\r\nDimensions (W x D x H)\tThickness: 0.41 to 1.61 cm (0.16 to 0.63 inches); Width: 30.41 cm (11.97 inches); Depth: 21.24 cm (8.36 inches)\r\n\r\nWeight\t1.29 kg (2.8 lbs)\r\n\r\nIncluded in the Box\tMacBook Air; 30W USB-C Power Adapter; USB-C Charge Cable (2 m)\r\n\r\nWarranty \t01 year International Limited Warranty (Terms & Condition Apply As Per Apple)",
"image": "/images/macbook_IU3NvNF.jpg",
"created_at": "2022-08-19T17:42:13.118095Z",
"updated_at": "2022-08-19T17:42:13.118095Z",
"stock": true,
"category": 1,
"user": "mosta"
}]
How to approach to make this step?
import 'package:collection/collection.dart';
and use firstWhereOrNull;
example:
searchArray(String searchValue){
var test =
products.firstWhereOrNull((element) => element['name'].contains(searchValue));
print(test); //print just first object whos name property contains "MSI"
}
Or
searchArray(String searchValue) {
var test =
products.where((element) => element['name'].toString().contains(searchValue));
if (test != null) {
for (var testItem in test) {
print(testItem); //print all maps whos contains sV
}
}
}
Here is one of approach you can use to search some query through the list and add the result in another list using for in iterables
void search(String query) {
List<dynamic> searchResult = [];
for (final product in products) {
if (product["name"].toLowerCase().contains(query.toLowerCase())) {
searchResult.add(product);
print(searchResult);
return;
}
}
}
full code here
Or you can use firstWhereOrNull in dart collection as mentioned by Kendruu

MongoDB query to compute percentage

I am new to MongoDB and kind of stuck at this query. Any help/guidance will be highly appreciated. I am not able to calculate the percentage in the desired way. There is something wrong with my pipeline where prerequisites of percentage are not computed correctly. Following I provide my unsuccessful attempt along with the desired output.
Single entry in the collection looks like below:
_id : ObjectId("602fb382f060fff5419fd0d1")
time : "2019/05/02 00:00:00"
station_id : 3544
station_name : "Underhill Ave &; Pacific St"
station_status : "In Service"
latitude : 40.6804836
longitude : -73.9646795
zipcode : 11238
borough : "Brooklyn"
neighbourhood : "Prospect Heights"
available_bikes : 5
available_docks : 21
The query I am trying to solve is:
Given a station_id (e.g., 522) and a num_hours (e.g., 3) passed as parameters:
- Consider only the measurements where the station_status = “In Service”.
- Consider only the measurements for that concrete
“station_id”.
- Compute the percentage of measurements with
available_bikes = 0 for each hour of the day (e.g., for the period
[8am, 9am) the percentage is 15.06% and for the period [9am, 10am)
the percentage is
27.32%).
- Sort the percentage results in decreasing order.
- Return the top “num_hours” documents.
The desired output is:
--- DOCUMENT 0 INFO ---
---------------------------------
hour : 19
percentage : 65.37
total_measurements : 283
zero_bikes_measurements : 185
---------------------------------
--- DOCUMENT 1 INFO ---
---------------------------------
hour : 21
percentage : 64.79
total_measurements : 284
zero_bikes_measurements : 184
---------------------------------
--- DOCUMENT 2 INFO ---
---------------------------------
hour : 00
percentage : 63.73
total_measurements : 284
zero_bikes_measurements : 181
My attempt is:
command_1 = {"$match": {"station_status": "In Service", "station_id": station_id, "available_bikes": 0}}
my_query.append(command_1)
command_2 = {"$group": {"_id": "null", "total_measurements": {"$sum": 1}}}
my_query.append(command_2)
command_3 = {"$project": {"_id": 0,
"station_id": 1,
"station_status": 1,
"hour": {"$substr": ["$time", 11, 2]},
"available_bikes": 1,
"total_measurements": {"$sum": 1}
}
}
my_query.append(command_3)
command_4 = {"$group": {"_id": "$hour", "zero_bikes_measurements": {"$sum": 1}}}
my_query.append(command_4)
command_5 = {"$project": {"percent": {
"$multiply": [{"$divide": ["$total_measurements", "$zero_bikes_measurements"]},
100]}}}
my_query.append(command_5)
I've taken a look at this and I'm going to offer some sincere advice:
Don't try and do this in an aggregate query. Just go back to basics and pull the numbers out using find()s and then calculate the numbers in python.
If you want to persist with an aggregate query, I will say that your match command filters on available_bikes equal to zero. You never have the total number of measurements, so you can never find the percentage. Also when you have done your first $group, your "lose" your projection so at that point in the pipeline you only have total_measurements and that's it (comment out the commands 3 to 5 to see what I mean).

Mongodb find documents

I have a MongoDB instance which contains a translation of texts:
{
"_id" : ObjectId("57c68ba415f4d42b6ecd9ee7"),
"en" : "Adana (pronounced [aˈda.na]) is a major city in southern Turkey. The city is situated on the Seyhan river, 35 km (22 mi) inland from the Mediterranean Sea, in south-central Anatolia. It is the administrative seat of the Adana Province and has a population of 1.7 million,[1] making it the fifth most populous city in Turkey. Adana-Mersin polycentric metropolitan area, with a population of 3 million, stretches over 70 km (43 mi) east-west and 25 km (16 mi) north-south; encompassing the cities of Mersin, Tarsus and Adana.",
"sw" : "Adana (Kigiriki Άδανα) ni mji mkubwa katika nchi ya Uturuki. Kwa mujibu wa sensa iliyofanyika mwaka wa 2000, mji una wakazi wapatao 1,130,710 waishio huko,[2] na kuufanya kuwa mmoja kati ya miji mitano mikubwa ya Uturuku (baada ya Istanbul, Ankara, İzmir na Bursa). Mwaka wa 2006 mji wa Adana umekadiriwa kufikia iadadi ya wakazi wapatao 1,271,894. Huu ndiyo mji mkuu wa Mkoa wa Adana."
}
{
"_id" : ObjectId("57c68ba915f4d42b6ecd9eea"),
"en" : "Addis Ababa or Addis Abeba (the spelling used by the official Ethiopian Mapping Authority),(Amharic: አዲስ አበባ? Addis Abäba IPA: [adˈdis ˈabəba] ( listen), \"new flower\"; Oromo: Finfinne,[3][4] [fɪnˈfɪ́n.nɛ́] \"Natural Spring(s)\"), is the capital and largest city of Ethiopia. Finfinne is its Oromo name. It has a population of 3,384,569 according to the 2007 population census, with annual growth rate of 3.8%. This number has been increased from the originally published 2,738,248 figure and appears to be still largely underestimated.[2][5]",
"sw" : "Addis Ababa (pia Addis Abeba; kwa Kiamhara አዲስ አበባ, \"Ua Jipya\"; kwa Kioromo Finfinne) ni mji mkuu wa Ethiopia na wa Umoja wa Afrika."
}
{
"_id" : ObjectId("57c68bab15f4d42b6ecd9eec"),
"en" : "Adelaide of Italy (931 – 16 December 999), also called Adelaide of Burgundy, was the second wife of Holy Roman Emperor Otto the Great[2] and was crowned as the Holy Roman Empress with him by Pope John XII in Rome on February 2, 962. Empress Adelaide was perhaps the most prominent European woman of the 10th century; she was regent of the Holy Roman Empire as the guardian of her grandson in 991-995.[2]",
"sw" : "Adelaide wa Italia (takriban 931 – 16 Desemba, 999) alikuwa binti wa Rudolf II, mfalme wa Burgundia. Kwanza aliolewa na Lothar, mfalme wa Italia. Alipofariki Lothar, Adelaide aliolewa na Otto I, mfalme wa Ujerumani. Aliishi maisha matakatifu. Sikukuu yake ni 16 Desemba."
}
What I would like to do is to select one specific record. For example I expect to select the last record by doing this:
db.wiki.find({"sw": "Adelaide wa Italia"}).pretty();
But the mongo shell returns nothing.
Indeed, I know that I can create an index and do something like:
db.wiki.find({$text: {$search: "\"Adelaide wa Italia\""}}).pretty();
which indeed returns the record as expected.
What am I doing wrong in the non-index searching please?
In this case you should use search with regex:
db.wiki.find({"sw": /Adelaide wa Italia/}).pretty();
The way you are doing it by:
db.wiki.find({"sw": "Adelaide wa Italia"}).pretty();
you simply tell Mongo to return you all documents where sw is equal to Adelaide wa Italia but you want to get all documents which contains this phrase in sw field instead.

Is there inherent interaction between odes when using matlab's ode45 function?

I am trying to model interaction (diffusion) between population in two blocks using Matlab's ODE45 function.
The population in each block is governed by the same set of ODEs, but has different initial conditions.
However, I find that even when there is no interaction term between the two blocks (such that they should be independent), the difference in initial conditions still seems to influence the populations in them. This means that, when calculated together, the populations in the blocks differ from when calculated separately. Is there an explanation for this?
I tried this with a very simple model for a proof of concept:
Function calls:
[t1,y1] = ode45(#equations, [1:20], [100; 50]); % block 1
[t2,y2] = ode45(#equations, [1:20], [100; 100]); % block 2
[t3,y3] = ode45(#equations2, [1:20], [100;50;100;100]); % (block 1, block 2)
Function modelling population in one block only:
function [dydt] = equations(t,y)
dydt = [(y(1) + 5*y(2)); ... %m
(-y(2) - 2*y(1)); ... %n
];
return
Function modelling both blocks, but without interaction:
function [dydt] = equations2(t,y)
dydt = [(y(1) + 5*y(2)); ... %m, block 1
(-y(2) - 2*y(1)); ... %n, block 1
(y(3) + 5*y(4)); ... %m, block 2
(-y(4) - 2*y(3)); ... %n, block 2
];
return
Result when two blocks calculated separately:
100 50 100 100
-82.5651126482403 -61.2399111160678 -70.8298703784238 -113.079426303262
63.5149326478799 71.2611808361777 40.2624466444427 123.919353592460
-43.1859556122909 -79.8393860152817 -8.90683490348150 -132.277927048621
21.9743397563556 86.8220697463693 -22.6303780909040 137.973908367664
-0.354918519359671 -92.0989416214417 53.7225657700143 -140.919984325956
-21.2629138588043 95.5352361959004 -83.7315196717762 141.098469411677
42.4644938860107 -97.0482785784471 112.050303306456 -138.445708319198
-62.8212058809813 96.6327114704933 -138.138533695681 133.012881410501
81.9247177241794 -94.3111553111835 161.481224015549 -124.963465578347
-99.3812030807478 90.1082810663461 -181.603255611880 114.429891038409
114.845927928453 -84.0902243542573 198.088587603452 -101.593579579227
-128.038489201868 76.4154884940680 -210.635351405432 86.7397437298800
138.675067137440 -67.2257825991193 219.018298709806 -70.1774427449607
-146.535410253369 56.6883955999672 -223.021403427644 52.2241854879404
151.485921591776 -45.0236010893207 222.530966569364 -33.2118012943491
-153.442292768067 32.4726456791801 -217.644899082991 13.5504349990489
152.321501615162 -19.2743265017041 208.457113276080 6.36250787673260
-148.144949801383 5.68381588482233 -195.066043293572 -26.1560882959426
141.024940766196 8.01698112966525 177.792461039602 45.4369626814643
Result when two blocks calculated together:
100 50 100 100
-82.5614380549815 -61.2386250164727 -70.8214933555803 -113.085294273425
63.4808523920134 71.2492107022344 40.2403909177619 123.906052225068
-43.1428254169980 -79.8465560431243 -8.86332933780633 -132.269515222896
21.9512910424390 86.8494877098212 -22.6803808332093 137.993637919124
-0.324547757386938 -92.1128384145929 53.7640196166716 -140.954822929939
-21.3110352832942 95.5328877966081 -83.7748031881502 141.094761269331
42.5230708505071 -97.0466778715188 112.116137495667 -138.418902426909
-62.8798722752104 96.6307163280550 -138.215550196187 132.992890319329
81.9803719854667 -94.2947890971016 161.559769097134 -124.926060504869
-99.4446392159052 90.0812551138450 -181.682036111080 114.372592711550
114.920836766971 -84.0716375263694 198.174987302179 -101.539954624572
-128.100385825296 76.3847285271368 -210.709163142815 86.6824352002572
138.720481894513 -67.1710769635203 219.033021842029 -70.0921219690280
-146.574502140440 56.6199063635580 -222.990477101486 52.1070327582791
151.516503440925 -44.9493339209586 222.520965582938 -33.0950981283072
-153.445319072891 32.3873778023315 -217.627693978053 13.4288556805328
152.307662312383 -19.1817679777499 208.387426508819 6.50027540164903
-148.121448302555 5.59183915228772 -194.975897304652 -26.2998808971022
140.970297553726 8.11485856302741 177.658703561865 45.5804419325655
How much different are the results? Ode45 is a method with step-size control. The computation of the local error that is used to control the step size will certainly be different (not necessarily better or worse) for the joint system. However, the resulting differences in the values should stay inside the relative and absolute tolerances used in the method, which by default are 1e-6. Using smaller tolerances should "decouple" the two systems to an according degree.
PS: Up to changes in the last displayed digit, the correct result should be
1 [ 100. 50. 100. 100. ]
2 [ -82.53524872 -61.2596255 -70.77524805 -113.11125047]
3 [ 63.41855387 71.29313918 40.13392902 123.95857849]
4 [ -43.03253624 -79.8997202 -8.68932914 -132.32487471]
5 [ 21.7852221 86.90710777 -22.92918773 138.04268767]
6 [ -0.101876596 -92.1750490 54.0887768 -140.997575 ]
7 [ -21.58350797 95.59810598 -84.16577854 141.1303955 ]
8 [ 42.83689848 -97.10776622 112.55820169 -138.43848988]
9 [ -63.23290817 96.67381387 -138.69777167 132.97573693]
10 [ 82.36331078 -94.30493447 162.06130481 -124.85147371]
11 [ -99.84521116 90.04854117 -182.18117983 114.2283074 ]
12 [ 115.32870896 -83.9898257 198.6546973 -101.31886073]
13 [-128.50390187 76.2500533 -211.15213965 86.38151638]
14 [ 139.1070883 -66.98413557 219.42337049 -69.71524539]
15 [-146.92604542 56.37752991 -223.30284108 51.65362329]
16 [ 151.80427675 -44.6425276 222.71290379 -32.55815357]
17 [-153.64414443 32.0140048 -217.66536621 12.81103218]
18 [ 152.40882353 -18.74472148 208.26125485 7.1925021 ]
19 [-148.12303898 5.10026242 -194.68879305 -27.05207841]
20 [ 140.87257081 8.64627842 177.21963374 46.37020718]
Both your runs already differ unacceptably in the first line.

How to create interactive chart with Rebol

I have this code to create a candlestick chart in rebol. Now I'd like to use over feel http://www.rebol.com/how-to/feel.html#section-6 to show info on each candlestick but my box is drawn with draw dialect and it doesn't seem to accept event ?
plot: [
pen green line 5x404 5x440 pen gold fill-pen 0.255.0 box 3x424 7x418 line 10x396 10x422 pen gold fill-pen 0.255.0 box 8x418 12x402 line 15x397 15x436 pen gold fill-pen 255.0.0 box 13x401 17x435 line 20x429 20x447 pen gold fill-pen 255.0.0 box 18x434 22x446 line 25x441 25x464 pen gold fill-pen 255.0.0 box 23x446 27x463 line 30x445 30x493 pen gold fill-pen 255.0.0 box 28x461 32x482 line 35x470 35x504 pen gold fill-pen 255.0.0 box 33x481 37x492 line 40x466 40x498 pen gold fill-pen 0.255.0 box 38x491 42x477
]
grid: [1100 600]
step-grid: 5
max-n-points: (grid/1 / step-grid) - 1
x-axis-border: 20
Y-margin: 10
X0: 5
grid-color: coal
main: layout [
origin 20x0
space 1x1
panel1: box 1100x580 black effect reduce [
'line-pattern 4 4
'grid 30x30 0x0 (grid-color)
'draw plot
]
panel2: box 1100x0 black
panel3: box 1100x20 black
]
view main
Here is a little expansion of my previous answer related to your chart viewer.
there are many ways you may adapt it, but it should give you some ideas into solving your problem.
rebol []
plot: []
data: reduce [ ]
refresh: func [/local clr delta prev-pos pos] [
clear plot
prev-pos: 0x300
foreach [clr delta] data [
pos: prev-pos + (delta * 0x1) + 7x0
append plot compose [
pen (clr) line (prev-pos) (pos) fill-pen (clr) pen none circle dot-size (pos)
]
prev-pos: pos
]
show panel1
]
add-data: func [i][loop i [append data reduce [(random white * .85) + (white * .15) (-20 + random 40)]] refresh]
grid: [800 600]
step-grid: 5
max-n-points: (grid/1 / step-grid) - 1
x-axis-border: 20
Y-margin: 10
X0: 5
grid-color: coal
dot-size: 3
viewer-size: 800x580
; open up console before vid window
main: layout [
origin 20x0
space 1x1
field 800
panel1: box viewer-size black rate 30 effect [
line-pattern 4 4
grid 30x30 0x0 grid-color
draw plot
] feel [
;probe first panel1
over: func [face over? offset /local d][
panel1/pane: either over? [info-pane][none]
if over? [
d: offset/x - face/offset/x - 1
d: (to-integer d / 7) * 2 + 1
either d: pick data d [
info-box/text: to-string d
][
panel1/pane: none
]
]
]
engage: func [face action event] [
switch action [
down [
drag-start: event/offset
]
up [
drag-end: event/offset
scroll-size: to-integer abs ((pick (drag-start - drag-end) 1) / 5)
]
time [
info-box/offset: event/offset - 20x20 ; the offset is the main-window origin
show main
]
]
]
]
panel2: box 800x0 black
panel3: box 800x20 black
]
insert-event-func [
either all [
event/type = 'key
none? system/view/focal-face
][
print ["shortcut: " event/key]
switch event/key [
; escape
#"^[" [quit]
; enter/return
#"^M" [print "resampling data" clear data add-data 100]
up [dot-size: dot-size + 1 show panel1]
down [dot-size: dot-size - 1 show panel1]
left [clear skip tail plot -12 clear skip tail data -2 show panel1]
right [add-data 2]
]
none
][
event
]
]
info-box: make face [
offset: 0x0
color: white * .2
size: 150x30
text: "0.0.0"
font: make font [valign: 'middle style: [bold italic]]
]
info-pane: reduce [info-box]
add-data 100
refresh
view/options main [all-over]
focus panel1
Note that as we move the mouse over the chart, we are only using the X component of the mouse to figure out what to display. Better systems are obvious, but this is sufficient to illustrate what needs to be done to receive all mouse move events and act on them.
Also note that the over feel receives Window offsets, so you must remove the face's offset to get the real face-relative coordinates.
PS: The red arrow above, is my mouse cursor.