Find an embedded document in mongodb - mongodb

Here is my mongo database
db.employee.insert(
{
_id: 'shop2',
ShopName: 'Gala',
ShopAddress: 'Kilmeaden',
Owner: 'Bryan Power',
ShopContactNumber: '08766442365',
Employee: [
{
EmployId: '4',
EmployName: 'Adam Byrne',
EmployContactNumber: 08688972,
EmployAddress: 'Bawnfune',
Salary: 250.00,
Hours: 25,
Wage: 9.00,
EmployeeType: 'FloorStaff'
},
{
EmployId: '5',
EmployName: 'Shane Power',
EmployContactNumber: 0873347584,
EmployAddress: 'Portlaw',
Salary: 350.00,
Hours: 32,
PayType: 'Bank',
Wage: 8.65,
EmployeeType: 'FloorStaff'
},
{
EmployId: '6',
EmployName: 'Jackie Legs',
EmployContactNumber: 0861231237,
EmployAddress: 'Ballyduff',
Salary: 550.00,
Hours: 32,
PayType: 'Cheque',
Wage: 11.60,
EmployeeType: 'Manager'
}
]});
I am trying to access the sub document of this insert statement to retrieve the EmployName, Salary and hours. Here is what I have been trying to do but it returns all three sub documents instead. Can I isolate these particular values?
db.employee.find({"Employee.EmployId": ""},
{
"Employee.EmployName":"Adam Byrne",
"Employee.Salary": 250.00,
"Employee.Hours":25
}).pretty();

Related

MongoDb Query from nested documents

{ _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

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

How can I query all when using Pymongo, group? not using accumulation?

I am making a restful api based on flask and Pymongo. Been trying to query data in a specific shape but having a hard time querying it. Below is my query code.
def track_route(from_time, to_time):
doc = myCol.aggregate([
{"$match":{
"MessageTime":{"$gt": from_time},
"MessageTime":{"$lt": to_time}
}},
{"$group":{
"_id":'$MMSI',
"$MMSI":{"accumulator1":"$ROT"}
}},
{"$project":{"_id":0}}
])
doc_list = [i for i in doc]
return doc_list
It returns this.
pymongo.errors.OperationFailure: The field '$MMSI' must be an accumulator object, full error: {'ok': 0.0, 'errmsg': "The field '$MMSI' must be an accumulator object", 'code': 40234, 'codeName': 'Location40234'}
This is the shape that I want to return.
[
{
123456789: [
{
MessageTime: '2021-05-28 17:29:22',
BaseStationID: '999999',
MsgType: '11',
mode: '3',
ROT: '0',
SOG: '0.0',
PosAcc: '0',
lon: '99.32404166666667',
lat: '93.47150833333333',
COG: '99.9',
Heading: '68',
MessageTimeU: '1622190562',
},
{
MessageTime: '2021-05-28 17:48:57',
BaseStationID: '4999314',
MsgType: '11',
mode: '1',
ROT: '0',
SOG: '17.7',
PosAcc: '1',
lon: '99.48246666666667',
lat: '9.980546666666667',
COG: '999.0',
Heading: '341',
MessageTimeU: '1622191737',
},
{
MessageTime: '2021-05-28 13:16:50',
BaseStationID: '999914',
MsgType: '11',
mode: '1',
ROT: '-128',
SOG: '0.1',
PosAcc: '1',
lon: '999.531585',
lat: '99.52044166666666',
COG: '998.2',
Heading: '511',
MessageTimeU: '1622175410',
},
{
MessageTime: '2021-05-28 11:45:43',
BaseStationID: '9903702',
MsgType: '11',
mode: '4',
ROT: '0',
SOG: '9.4',
PosAcc: '0',
lon: '99.51709333333334',
lat: '9.952831833333333',
COG: '00.9',
Heading: '511',
MessageTimeU: '1622169943',
},
],
},
{
234567890: [
{
MessageTime: '2021-05-28 20:59:52',
BaseStationID: '000702',
MsgType: '11',
mode: '1',
ROT: '-128',
SOG: '0.0',
PosAcc: '1',
lon: '00.46612166666667',
lat: '00.507135',
COG: '360.0',
Heading: '511',
MessageTimeU: '1622203192',
},
{
MessageTime: '2021-05-28 09:41:51',
BaseStationID: '0003702',
MsgType: '11',
mode: '1',
ROT: '-128',
SOG: '4.5',
PosAcc: '1',
lon: '00.26525833333334',
lat: '00.44930333333333',
COG: '238.7',
Heading: '511',
MessageTimeU: '1622162511',
},
{
MessageTime: '2021-05-28 17:48:50',
BaseStationID: '0003702',
MsgType: '11',
mode: '3',
ROT: '-128',
SOG: '0.0',
PosAcc: '0',
lon: '00.258005',
lat: '00.41504833333333',
COG: '00.4',
Heading: '511',
MessageTimeU: '1622191730',
},
{
MessageTime: '2021-05-28 14:27:42',
BaseStationID: '0003702',
MsgType: '11',
mode: '4',
ROT: '0',
SOG: '7.1',
PosAcc: '1',
lon: '00.260425',
lat: '00.418685',
COG: '65.0',
Heading: '511',
MessageTimeU: '1622179662',
},
],
},
];
123456789 and 234567890 are the MMSI value and are the key value for sub documents. How can I query in the shape above? It's nested. If cannot, at least the most similar way.
You have some mistakes in your aggregation, you cannot reference a field as a key, you should put a static field name.
This a correct way to group.
db.collection.aggregate({
"$group": {
"_id": "$MMSI",
"a": { //replace that "a" with any field name you want but not for a $ref
"$push": "$$ROOT" // you need to use an accumulator like $push, and the correct form to reference the whole doc is $$ROOT
}
}
}
Then you can map your info as you wanted. You can test the code here
{
"$replaceRoot": {
"newRoot": {
$arrayToObject: {
$map: {
input: [
"$$ROOT"
],
as: "el",
in: {
"k": {
$toString: "$$el._id"
},
"v": "$$el.a"
}
}
}
}
}
}

Laravel Eloquent using 'with' and 'where'

Using Laravel 5.4
I am reaching out as I am having a difficult time wrapping my head around this and after searching all day on the internet (and stackoverflow) I have not found a good solution to my problem that works.
Basically, I have a user object, that queries a child object which in turn includes a child object and I need to filter with where on that grandchild object.
It looks like this:
User =>
Pet(1) =>
PetServiceItem <= ServiceItem(1)
PetServiceItem <= ServiceItem(2)
PetServiceItem <= ServiceItem(3)
Pet(2) =>
PetServiceItem <= ServiceItem(1)
PetServiceItem <= ServiceItem(4)
PetServiceItem <= ServiceItem(5)
I'll post the relevant parts of the information so someone can tell me how this might be done.
User Model
class User extends Authenticatable
{
public function pets()
{
return $this->hasMany(Pet::class);
}
}
Pet Model
class Pet extends Model
{
protected $fillable = [
'id',
'user_id',
...];
public function user()
{
return $this->belongsTo(User::class);
}
public function petServiceItems(){
return $this->hasMany(PetServiceItem::class);
}
}
PetServiceItem model
class PetServiceItem extends Model
{
protected $fillable = [
'pet_id',
'service_item_id',
'approved'
];
protected $table = 'pet_service_item';
public function pet()
{
return $this->belongsTo(Pet::class);
}
public function serviceItem()
{
return $this->belongsTo(ServiceItem::class);
}
}
ServiceItem model
class ServiceItem extends Model
{
protected $fillable = [
'id',
...,
'start_date',
'end_date',
'...',
];
public function pets(){
return $this->hasMany(PetServiceItem::class);
}
}
Using Tinker I can do the following:
$user->pets()->with(['petServiceItems', 'petServiceItems.service'])->get()
And get this data:
=> Illuminate\Database\Eloquent\Collection {#1118
all: [
App\Pet {#1120
id: 1,
user_id: 6,
name: "Coco",
slug: "carol!coco",
image: "/dist/images/pets/carol/coco.jpg",
breed: null,
color: null,
gender: "Female",
birthdate: "2013-07-06 03:58:46",
fixed: 0,
weight: "48",
licensed: "",
tattoo: "",
microchip: "",
created_at: "2017-07-17 17:37:54",
updated_at: "2017-07-17 17:37:54",
petServiceItems: Illuminate\Database\Eloquent\Collection {#1126
all: [
App\PetServiceItem {#1132
id: 1,
provider_id: 2,
pet_id: 1,
service_item_id: 1,
approved: 1,
created_at: "2017-07-17 17:37:57",
updated_at: "2017-07-17 17:37:57",
serviceItem: App\ServiceItem {#1137
id: 1,
provider_id: 2,
type: "WALK",
subtype: "",
title: "7am 30min Walk between 7am and 10am",
desc: "Daily weekday walks between 7am and 10am",
day1: 0,
day2: 1,
day3: 1,
day4: 1,
day5: 1,
day6: 1,
day7: 0,
needs_approval: 0,
start_date: "2017-07-17 00:00:00",
end_date: "2017-10-17 00:00:00",
all_day: 0,
start_time: "07:00:00",
end_time: "10:00:00",
duration: 30,
pricing_one: 2000,
pricing_twoplus: 1800,
created_at: "2017-07-17 17:37:57",
updated_at: "2017-07-17 17:37:57",
deleted_at: null,
},
},
App\PetServiceItem {#1134
id: 3,
provider_id: 2,
pet_id: 1,
service_item_id: 4,
approved: 0,
created_at: "2017-07-17 17:37:57",
updated_at: "2017-07-17 17:37:57",
serviceItem: App\ServiceItem {#1139
id: 4,
provider_id: 2,
type: "AGILITY",
subtype: "",
title: "10am Agility Tu/Th",
desc: "Agility class # 10am Tuesdays and Thursdays for 90 minutes",
day1: 0,
day2: 0,
day3: 1,
day4: 0,
day5: 1,
day6: 0,
day7: 0,
needs_approval: 1,
start_date: "2017-07-17 00:00:00",
end_date: "2017-09-17 00:00:00",
all_day: 0,
start_time: "10:00:00",
end_time: "11:30:00",
duration: 90,
pricing_one: 5000,
pricing_twoplus: 4500,
created_at: "2017-07-17 17:37:57",
updated_at: "2017-07-17 17:37:57",
deleted_at: null,
},
},
],
},
},
App\Pet {#1123
id: 2,
user_id: 6,
name: "Ruby",
slug: "carol!ruby",
image: "/dist/images/pets/carol/ruby.jpg",
breed: null,
color: null,
gender: "Female",
birthdate: "2012-06-16 22:47:43",
fixed: 1,
weight: "53",
licensed: "",
tattoo: "",
microchip: "",
created_at: "2017-07-17 17:37:54",
updated_at: "2017-07-17 17:37:54",
petServiceItems: Illuminate\Database\Eloquent\Collection {#1119
all: [
App\PetServiceItem {#1133
id: 2,
provider_id: 2,
pet_id: 2,
service_item_id: 1,
approved: 1,
created_at: "2017-07-17 17:37:57",
updated_at: "2017-07-17 17:37:57",
serviceItem: App\ServiceItem {#1137},
},
App\PetServiceItem {#1135
id: 4,
provider_id: 2,
pet_id: 2,
service_item_id: 4,
approved: 0,
created_at: "2017-07-17 17:37:57",
updated_at: "2017-07-17 17:37:57",
serviceItem: App\ServiceItem {#1139},
},
],
},
},
],
}
Now I need to do a where clause on the ServiceItem for the start_date.
I tried:
$user->pets()->with(['petServiceItems', 'petServiceItems.serviceItem'])->where('service_items.start_date', '>=', '2017-01-01')->get()
But, I get this error:
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'service_items.start_date' in
'where clause' (SQL: select * from pets where pets.user_id = 6
and pets.user_id is not null and service_items.start_date >=
2017-01-01)'
How can I use the where clause (or something else if needed) to filter the data I need?
edited:
I have figured out that this is the SQL that I want (or close enough approximation):
select * from users
join (select * from pets) pet on users.id = pet.user_id
join (select * from pet_service_item) psi on psi.pet_id = pet.id
join (select * from service_items) si on si.id = psi.service_item_id
join (select * from providers) prov on prov.id = si.provider_id
where si.start_date >= '2017-07-17'
AND si.end_date <= '2017-10-18'
AND prov.id = 2
AND users.id = 6
Where clause use the name of the table and not the model. Try this:
$user->pets()->with(['petServiceItems', 'petServiceItems.serviceItem'])
->where('service_items.start_date', '>=', '2017-01-01')->get();
So, I'm posting this as I never really did get an answer and I ended up with a solution, but not exactly the one I was looking for.
If anyone is interested, in the end, this is how I did it (note: this flattened the data, which for all intents and purposes, worked fine in my scenario).
$services = App\ServiceItem::where('provider_id', '=', $provider->id)
->where('user.user_id', '=', $user->id)
->where('start_date', '<=', $end_date)
->where('end_date', '>=', $start_date)
->orWhereNull('end_date')
->where('pet.pet_user_id', '=', $user->id)
->whereNull('service_items.deleted_at')
->whereNUll('pet.pet_deleted_at')
->join(DB::raw('(select pet_id as psi_pet_id, service_item_id as psi_service_item_id from pet_service_items) psi'), function($join) {
$join->on('psi.psi_service_item_id', '=', 'service_items.id');
})
->join(DB::raw('(select id as pet_id, user_id as pet_user_id, name as pet_name, deleted_at as pet_deleted_at from pets) pet'), function($join) {
$join->on('pet.pet_id', '=', 'psi.psi_pet_id');
})
->join(DB::raw('(select id as user_id, name as user_name, deleted_at as user_deleted_at from users) user'), function($join) {
$join->on('user.user_id', '=', 'pet.pet_user_id');
});
return ['status' => 200, 'services' => $services->get()];

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'
}
});