MongoDb Query from nested documents - mongodb

{ _id: ObjectId("62d3af6d0df67535575ee87e"),
time: '2022-07-17T09_39_19',
data:
[ { Manufacturer: 'iPollo',
Model: 'V1',
Release: 'June 2022',
'Size(mm)': { x: 314, y: 194, z: 290 },
'Weight(g)': 13000,
'Noise level': '70db',
'Fan(s)': '4',
'Power(w)': 3100,
Interface: 'Ethernet',
Memory: '6G',
Temperature: '5 - 25 °C',
Humidity: '10 - 90 %',
coins:
[ 'Ubiq',
'Ethereum',
'Ethereum Classic',
'Musicoin',
'Pirl',
'EtherGem',
'Callisto',
'QuarkChain' ],
available_stores:
[ { store_name: 'CoinMining Central',
url: 'https://coinminingcentral.com/collections/ipollo-miners/products/ipollo-v1-mini-ethereum-miner-3-6-gh-s?ref=uybdgyQD&ref=uybdgyQD',
price: '$21,959.49',
country: 'United Kingdom',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'AKMiner',
url: 'https://www.akminer.com/all-products/ipollo-v1-3600mh-eth-miner-most-powerful-eth-miner-for-2022?wpam_id=1',
price: '$20,399.00',
country: 'China',
stock: 'In stock(3 \ndays\n)',
isFreeShipping: false },
{ store_name: 'NHASH',
url: 'https://www.nhash.net/miners/94129954756763648?ref=3yrntphlqn',
price: '$20,999.00',
country: 'Hong Kong',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'BT-Miners',
url: 'https://bt-miners.com/products/2022-new-ipollo-v1-eth-etc-miner-3600mh-s-with-psu-and-cord-most-powerful-eth-miner-for-2022?ref=3yrntphlqn&ref=3yrntphlqn&variant=43048045183163',
price: '$21,000.00',
country: 'United States',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'ViperaTech',
url: 'https://www.viperatech.com/product/ipollo-v1-eth-etc-miner-3600mh-s/?ref=585',
price: '$21,900.00',
country: 'Canada',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'Safety Miner',
url: 'https://www.safetyminer.net/product-page/ipollo-v1-3-6gh-s?ref=3yrntphlqn',
price: '$25,103.16',
country: 'United Kingdom',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'Miner Bros',
url: 'https://www.cryptominerbros.com/product/ipollo-v1-3600mh-s-eth-etc-miner/?wpam_id=1',
price: '$27,499.00',
country: 'Honk Kong',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'AsicMarketPlace',
url: 'https://asicmarketplace.com/product/ipollo-v1-eth-miner-3600mh/?wpam_id=4',
price: '$27,550.00',
country: 'Honk Kong',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'MillionMiner',
url: 'https://www.millionminer.com/ipollo-v1-3600mhs--ethereum-miner-new-millionminercom.html?1000',
price: '$30,143.96',
country: 'Germany',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'Crypto Supply',
url: 'https://cryptosupply.de/product/ipollo-v1/?wpam_id=1',
price: '$30,900.08',
country: 'Germany',
stock: 'In stock(14 \ndays\n)',
isFreeShipping: false },
{ store_name: 'Casa Miners',
url: 'https://casaminers.com/collections/new-asic-1/products/ipollo-v1-3-6gh-s?ref=TTdMmJZNqvqtBI',
price: '$31,242.85',
country: 'Italia',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'iPollo',
url: 'https://ipollo.com/products/ipollo-v?ref=3yrntphlqn',
price: '$35,460.00',
country: 'China',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'Bitcoin Merch',
url: 'https://bitcoinmerch.com/products/ipollo-v1-3-6gh-s-eth-asic-miner?aff=2',
price: '$39,999.99',
country: 'United States',
stock: 'Out of stock',
isFreeShipping: false } ],
Algorithm_and_power:
[ { Algorithm_name: 'EtHash',
'hashrate(H/hour) ': 3600000000,
'power_consumption(W)': 3100 } ],
available_mining_pools:
[ { pool_name: 'Poolin',
url_link: 'https://www.poolin.com',
profit_type: 'FPPS',
profit_perc: 'FPPS' },
{ pool_name: 'SparkPool',
url_link: 'https://www.sparkpool.com/',
profit_type: 'PPS',
profit_perc: 0.01 },
{ pool_name: 'Ethermine',
url_link: 'https://ethermine.org',
profit_type: 'PPLNS',
profit_perc: 0.01 },
{ pool_name: 'ViaBTC',
url_link: 'https://pool.viabtc.com?refer=731218',
profit_type: 'PPS+',
profit_perc: 0 },
{ pool_name: 'F2Pool',
url_link: 'https://www.f2pool.com',
profit_type: 'PPS+',
profit_perc: 0.03 } ] },
{ Manufacturer: 'Jasminer',
Model: 'X4',
Release: 'November 2021',
'Noise level': '75db',
'Fan(s)': '4',
'Power(w)': 1200,
Interface: 'Ethernet',
Memory: '5G',
Temperature: '5 - 40 °C',
Humidity: '5 - 95 %',
coins:
[ 'Ubiq',
'Ethereum',
'Ethereum Classic',
'Musicoin',
'Pirl',
'EtherGem',
'Callisto',
'QuarkChain' ],
available_stores:
[ { store_name: 'Safety Miner',
url: 'https://www.safetyminer.net/product-page/jasminer-x4-2-6gh-1200w?ref=3yrntphlqn',
price: '$20,163.18',
country: 'United Kingdom',
stock: 'Out of stock',
isFreeShipping: false },
{ store_name: 'Jingle Mining',
url: 'https://www.jinglemining.com/products/jasminer-x4-etchash-server?ref=3yrntphlqn&variant=42041025233122',
price: '$20,499.00',
country: 'China',
stock: 'Pre-order(Jun 2022)',
isFreeShipping: false },
{ store_name: 'ViperaTech',
url: 'https://www.viperatech.com/product/jasminer-x4-etchash-server/?ref=585',
price: '$21,000.00',
country: 'Canada',
stock: 'In stock',
isFreeShipping: false },
{ store_name: 'AKMiner',
url: 'https://akminer.com/all-products/jasminer-x4-etchash-server-jan-shipment?wpam_id=1',
price: '$23,999.00',
country: 'China',
stock: 'Used',
isFreeShipping: false },
{ store_name: 'BT-Miners',
url: 'https://bt-miners.com/collections/eth-miners/products/jasminer-x4-etc-eth-5g-miner-2500mh-s-mine-eth-till-june-2022?ref=3yrntphlqn&ref=3yrntphlqn&variant=42969029378235',
price: '$24,459.00',
country: 'United States',
stock: 'Used',
isFreeShipping: false },
{ store_name: 'NHASH',
url: 'https://www.nhash.net/miners/99141979488657408?ref=3yrntphlqn',
price: '$24,999.00',
country: 'Hong Kong',
stock: 'Pre-order(May 2022)',
isFreeShipping: false },
{ store_name: 'CoinMining Central',
url: 'https://coinminingcentral.com/collections/jasminer/products/jasminer-x4-eth-ethereum-miner-2500mh?ref=uybdgyQD',
price: '$29,674.99',
country: 'United Kingdom',
stock: 'Pre-order(Jul 2022)',
isFreeShipping: false },
{ store_name: 'Bitcoin Merch',
url: 'https://bitcoinmerch.com/products/jasminer-x4-2-5-gh-s-ethereum-miner?aff=2',
price: '$51,999.99',
country: 'United States',
stock: 'In stock(30 \ndays\n)',
isFreeShipping: false } ],
Algorithm_and_power:
[ { Algorithm_name: 'EtHash',
'hashrate(H/hour) ': 2500000000,
'power_consumption(W)': 1200 },
{ Algorithm_name: 'EtHashETC',
'hashrate(H/hour) ': 2500000000,
'power_consumption(W)': 1200 } ],
available_mining_pools:
[ { pool_name: 'Poolin',
url_link: 'https://www.poolin.com',
profit_type: 'FPPS',
profit_perc: 'FPPS' },
{ pool_name: 'SparkPool',
url_link: 'https://www.sparkpool.com/',
profit_type: 'PPS',
profit_perc: 0.01 },
{ pool_name: 'Ethermine',
url_link: 'https://ethermine.org',
profit_type: 'PPLNS',
profit_perc: 0.01 },
{ pool_name: 'ViaBTC',
url_link: 'https://pool.viabtc.com?refer=731218',
profit_type: 'PPS+',
profit_perc: 0 },
{ pool_name: 'F2Pool',
url_link: 'https://www.f2pool.com',
profit_type: 'PPS+',
profit_perc: 0.03 } ] },
I have this collection in my mongodb database, and when I query data from it, like for example .find("data.Manufacturer":"iPollo") because its nested documents, it returns for me the entire document, is there any way where I could return only the object from the array without like hardcoding it (getting the entire data liste and iterate through it to find the query I am searching for)

One option is using an aggregation pipeline:
db.collection.aggregate([
{$match: {"data.Manufacturer": "iPollo"}},
{$set: {
data: {
$filter: {
input: "$data",
cond: {$eq: ["$$this.Manufacturer", "iPollo"]}
}
}
}
},
{$replaceRoot: {newRoot: {$first: "$data"}}}
])
See how it works on the playground example

Related

How to get a field of an object in document?

I am not sure how to phrase this question properly but basically I have an "Order" Schema and each order model contains an array of product objects created using "Product" Schema
When I create an order, my req.body is this
body: {
orderItems: [ [Object] ],
shippingAddress: {
fullName: '123',
address: '1231',
city: '123',
postalCode: '123',
country: '123'
},
shippingPrice: 0,
paymentMethod: 'Stripe',
itemsPrice: 338,
totalPrice: 338
},
If I log req.body.orderItems, I can see each product object printed
{
_id: new ObjectId("62d51a3895cad3ca283302f3"),
name: 'Christmas Cake',
slug: 'christmas-cake',
image: '/images/cake.jpg',
shop: 'Custom Cakes',
category: 'food',
description: 'Custom baked christmas cake, pre-order needed.',
price: 70,
stock: 1,
rating: 3,
numReviews: 2,
__v: 2,
createdAt: 2022-07-18T08:30:48.931Z,
updatedAt: 2022-07-20T03:03:00.592Z,
}
{
_id: new ObjectId("62d7a8c126dcacfc13055e3d"),
name: 'cake',
slug: 'cake',
image: '/images/cake.jpg',
shop: 'Custom Cakes',
category: 'food',
description: 'cake',
price: 15,
stock: 2,
rating: 0,
numReviews: 0,
user: { _id: new ObjectId("62d51d57c08cd7e6675e8d45")},
reviews: [],
createdAt: 2022-07-20T07:03:29.372Z,
updatedAt: 2022-07-20T07:03:59.315Z,
__v: 0
}
But I am unable to obtain the 'shop' field. req.body.orderItems.shop returns undefined

Strapi mongodb project specific fields in embedded documents

I'm trying to select especific fields from this document
{
_id: 60d9295db34f1c0144c9b8d4,
title: 'Este es el titulo',
slug: 'este-es-el-titulo',
date: '2021-06-27',
category: {
_id: 60d92921b34f1c0144c9b8d2,
title: 'Categoria 1',
slug: 'categoria-1',
id: '60d92921b34f1c0144c9b8d2'
},
cover: {
_id: 60d72c815e57e6015e38a4c7,
name: 'project4.png',
alternativeText: '',
caption: '',
hash: 'project4_3e8c906bdf',
ext: '.png',
mime: 'image/png',
size: 540.02,
width: 1895,
height: 883,
url: '/uploads/project4_3e8c906bdf.png',
formats: [Object],
provider: 'local',
related: [Array],
createdAt: 2021-06-26T13:32:49.389Z,
updatedAt: 2021-06-28T01:43:57.469Z,
__v: 0,
created_by: '60d69246c6f06d00f64312b0',
updated_by: '60d69246c6f06d00f64312b0',
id: '60d72c815e57e6015e38a4c7'
},
id: '60d9295db34f1c0144c9b8d4'
}
and I want get something like this:
{
_id: 60d9295db34f1c0144c9b8d4,
title: 'Este es el titulo',
slug: 'este-es-el-titulo',
date: '2021-06-27',
category: {
_id: 60d92921b34f1c0144c9b8d2,
title: 'Categoria 1',
slug: 'categoria-1',
id: '60d92921b34f1c0144c9b8d2'
},
cover: { url: '/uploads/project4_3e8c906bdf.png'}
id: '60d9295db34f1c0144c9b8d4'
}
I'm using Strapi with Mongodb and y was trying with the following code:
const requiredData = {
title: 1,
slug: 1,
date: 1,
category: 1,
cover: { url: 1 }
}
const populateData = [
{
path: 'category',
select: ['title', 'slug']
}
]
let editorsPick = await strapi.query('posts')
.model.find({ editorsPick: true}, requiredData)
.limit(3)
.populate(populateData)
But I only have this:
{
_id: 60d9295db34f1c0144c9b8d4,
title: 'Este es el titulo',
slug: 'este-es-el-titulo',
date: '2021-06-27',
category: {
_id: 60d92921b34f1c0144c9b8d2,
title: 'Categoria 1',
slug: 'categoria-1',
id: '60d92921b34f1c0144c9b8d2'
},
id: '60d9295db34f1c0144c9b8d4'
}
(Without cover image), and then try with:
let editorsPick = await strapi.query('posts')
.model.aggregate([
{"$match": { editorsPick: true}},
{"$project": requiredData}
])
But I got an empty array []
Please I need a little help, and sorry for my english

How to display multiple lines in eCharts using encode?

In eCharts, how do I modify the following option to show multiple lines in the chart? What I want is one line for product "Matcha Latte" and one line for "Cheese Cocao"? I would like to keep the dataset unchanged if possible.
option = {
legend: {},
tooltip: {},
dataset: {
dimensions: [{name:'product', type:'ordinal'}, {name:'date'},
{name:'value'}],
source: [
{product: 'Matcha Latte', 'date': 2016, 'value': 85.8},
{product: 'Matcha Latte', 'date': 2017, 'value': 73.4},
{product: 'Cheese Cocoa', 'date': 2016, 'value': 65.2},
{product: 'Cheese Cocoa', 'date': 2017, 'value': 53.9}
]
},
xAxis: {type: 'category', name: 'date'},
yAxis: {type: 'value', name: 'value'},
series: [
{type: 'line', encode: {x: 'date', y:'value'}},
]
};
you can you transform the dataset by using a filter:
option = {
legend: {},
tooltip: {},
dataset: [
{
dimensions: [
{ name: 'product', type: 'ordinal' },
{ name: 'date' },
{ name: 'value' }
],
source: [
{ product: 'Matcha Latte', date: 2016, value: 85.8 },
{ product: 'Matcha Latte', date: 2017, value: 73.4 },
{ product: 'Cheese Cocoa', date: 2016, value: 65.2 },
{ product: 'Cheese Cocoa', date: 2017, value: 53.9 }
]
},
{
fromDatasetIndex: 0,
transform: [
{
type: 'filter',
config: {
dimension: 'product',
value: 'Matcha Latte'
}
}
]
},
{
fromDatasetIndex: 0,
transform: [
{
type: 'filter',
config: {
dimension: 'product',
value: 'Cheese Cocoa'
}
}
]
}
],
xAxis: { type: 'category', name: 'date' },
yAxis: { type: 'value', name: 'value' },
series: [
{ datasetIndex: 1, type: 'line', encode: { x: 'date', y: 'value' } },
{ datasetIndex: 2, type: 'line', encode: { x: 'date', y: 'value' } }
]
};

Group by and retain original fields

I see in mongodb aggregations, specially in $group we can use accumulator to create new fields. But i want the old keys
Suppose i have this data
[
{ name: "My Plan 101", billingCycle: 'day', amount: 1, credits: 100, price: 7 },
{ name: "My Plan 102", billingCycle: 'day', amount: 1, credits: 150, price: 10 },
{ name: "My Plan 103", billingCycle: 'day', amount: 2, credits: 150, price: 15 },
{ name: "My Plan 104", billingCycle: 'month', amount: 3, credits: 150, price: 15 },
{ name: "My Plan 105", billingCycle: 'month', amount: 3, credits: 200, price: 20 },
]
Then the aggregation should be like
[
'day': {
'1': [{ name: 'My Plan 101' }, { name: 'My Plan 102' }],
'2': [{ name: 'My Plan 103' }]
},
'month': {
'3': [{ name: 'My Plan 104' }, { name: 'My Plan 105' }]
}
]
I tried a lot with mongodb aggregation but couldn't solve it so I used lodash for this.
let plans = await Plan.find()
plans = _.groupBy(plans, 'billingCycle');
for (const billingCyle in plans) {
let $plans = plans[billingCyle];
plans[billingCyle] = _.groupBy($plans, "amount")
}
console.log(plans)
The above snipped has solved my problem

Mongodb updating an embedded field

db.employee.insert(
{
_id: 'shop1',
ShopName: 'Londis',
ShopAddress: 'Clea boy',
Owner: 'Tim Byrne',
ShopContactNumber: '0877733121',
Employee: [
{
EmployId: '1',
EmployName: 'Pat Power',
EmployContactNumber: 0876395224,
EmployAddress: 'Lacka Rd',
Salary: 500.00,
Hours: 40,
PayType: 'Cheque',
Wage: 9.00,
EmployeeType: 'Manager'
},
{
EmployId: '2',
EmployName: 'Craig Coad',
EmployContactNumber: 0873347582,
EmployAddress: 'Portlaw',
Salary: 400.00,
Hours: 32,
PayType: 'Bank',
Wage: 8.65,
EmployeeType: 'FloorStaff'
},
{
EmployId: '3',
EmployName: 'Joe Bloggs',
EmployContactNumber: 0861234567,
EmployAddress: 'Waterford',
Salary: 510.00,
Hours: 12,
PayType: 'Cheque',
Wage: 9.50,
EmployeeType: 'Manager'
}]});
I want to update the state of an item for a specific Employee.
For example, I would want to update item 1 to set EmployName = "Patrick Power" for EmployeId = "1" because that employee exists:
db.students.update(
{'_id':'shop1','Employee.EmployId':'1'},
{$set:{'Employee.$.EmployName':'Patrick Power'} }
);
This is what i have been trying to do but it dose not work?
What am i doing wrong ?
This might be helpful to you :
db.collectionName.update({
"_id": "shop1",
'Employee': {
'$elemMatch': {
'EmployId': '1'
}
}
}, {
$set: {
'Employee.$.EmployName': 'Patrick Power'
}
});