Search This Blog

2023/05/17

MongoDb:$elemMatch,$slice,$push &$all & $size Operators

Today we will explore $elemMatch,$slice,$push &$all operators in mongoDb.
we will create a purchase collection for this.

Lets drop the 'purchase' collection if already exist

db.purchase.drop()

Now lets add documents to collection

db.purchase.insertMany( [
{
_id: 0,
email:"sagar@example.com",
purchaseTime:new Date("2024-01-01:12:30:00"),
cartItems: [
{ item_id: 43, quantity: 2, pricePerItem: 10 ,
dates:{ manifacturingDate: new Date("2023-10-10"),
expiryDate: new Date("2024-04-30")} },
{ item_id: 2, quantity: 15, pricePerItem: 240 ,
dates:{ manifacturingDate: new Date("2023-12-10"),
expiryDate: new Date("2024-06-30")} }
],
coshopper:["brother","wife","sister"],
deliveryAddress:{
city:"Mumbai",
street:"M k Gandhi Road",
pin:"400080",
town:"Vikroli",
Bldg:"Arun Niwara,Bldg No 167",
floor:"1st",
roomNo:"5386"
},
isDelivered:false
},
{
_id: 1,
email:"swara@example.com",
purchaseTime:new Date("2024-02-01:10:30:00"),
cartItems: [
{ item_id: 34, quantity: 5, pricePerItem: 20 ,
dates:{ manifacturingDate: new Date("2023-11-05"),
expiryDate:new Date("2024-07-20")}},
{ item_id: 56, quantity: 5, pricePerItem: 340 ,
dates:{ manifacturingDate: new Date("2023-11-05"),
expiryDate:new Date("2024-07-20")}},
{ item_id: 78, quantity: 3, pricePerItem: 540 ,
dates:{ manifacturingDate: new Date("2023-10-25"),
expiryDate:new Date("2024-08-29")}},
],
coshopper:["daughter","wife"],
deliveryAddress:{
city:"Mumbai",
street:"Indiara Gandhi Road",
pin:"400745",
town:"Naupada",
Bldg:"Arun Niwara,Bldg No 167",
floor:"1st",
roomNo:"3276"
},
isDelivered:true,
deliveryDate:new Date("2024-02-05:08:10:00"),
},
{
_id: 2,
email:"sangram@example.com",
purchaseTime:new Date("2024-01-05:14:35:00"),
cartItems: [
{ item_id: 23, quantity: 3, pricePerItem: 110 ,
dates:{ manifacturingDate: new Date("2023-12-15"),
expiryDate:new Date("2024-05-10")}},
{ item_id: 103, quantity: 4, pricePerItem: 5 ,
dates:{ manifacturingDate: new Date("2023-11-05"),
expiryDate:new Date("2024-07-09")}},
{ item_id: 38, quantity: 1, pricePerItem: 300 ,
dates:{ manifacturingDate: new Date("2023-12-25"),
expiryDate:new Date("2024-09-20")}},
],
coshopper:["daughter","friend"],
deliveryAddress:{
city:"Pune",
street:"Bose D K Road",
pin:"402357",
town:"Raja Nagar",
Bldg:"Varun CHS,Bldg No 546",
floor:"2nd",
roomNo:"785"
},
isDelivered:false
},
{
_id: 3,
email:"sachin@example.com",
purchaseTime:new Date("2024-01-01:08:24:00"),
cartItems: [
{ item_id: 4, quantity: 1, pricePerItem: 23 ,
dates:{ manifacturingDate: new Date("2023-11-05"),
expiryDate:new Date("2024-07-01")}},
{ item_id: 2, quantity: 1, pricePerItem: 240,
dates:{ manifacturingDate: new Date("2023-10-18"),
expiryDate:new Date("2024-03-20")}},
],
coshopper:["wife","sister-in-law","daughter"],
deliveryAddress:{
city:"Nashik",
street:"Jangli Maharaj Road",
pin:"2345765",
town:"Vartak Nagar",
Bldg:"Govardhan Das Apt,Bldg No 796",
floor:"8nd",
roomNo:"6885"
},
isDelivered:false
}
] )

The $elemMatch:
operator matches documents that contain an array field with at
least one element that matches all the specified query criteria.

Condition 1:

Finding all documents where they have purchased atleast one item with id 2.

db.purchase.find({
cartItems:{$elemMatch:{item_id:{$eq:2}}}
})

Output:
[
{
_id: 0,
email: 'sagar@example.com',
purchaseTime: ISODate('2024-01-01T07:00:00.000Z'),
cartItems: [
{
item_id: 43,
quantity: 2,
pricePerItem: 10,
dates: {
manifacturingDate: ISODate('2023-10-10T00:00:00.000Z'),
expiryDate: ISODate('2024-04-30T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 15,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-12-10T00:00:00.000Z'),
expiryDate: ISODate('2024-06-30T00:00:00.000Z')
}
}
],
coshopper: [ 'brother', 'wife', 'sister' ],
deliveryAddress: {
city: 'Mumbai',
street: 'M k Gandhi Road',
pin: '400080',
town: 'Vikroli',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '5386'
},
isDelivered: false
},
{
_id: 3,
email: 'sachin@example.com',
purchaseTime: ISODate('2024-01-01T02:54:00.000Z'),
cartItems: [
{
item_id: 4,
quantity: 1,
pricePerItem: 23,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-01T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 1,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-10-18T00:00:00.000Z'),
expiryDate: ISODate('2024-03-20T00:00:00.000Z')
}
}
],
coshopper: [ 'wife', 'sister-in-law','daughter' ],
deliveryAddress: {
city: 'Nashik',
street: 'Jangli Maharaj Road',
pin: '2345765',
town: 'Vartak Nagar',
Bldg: 'Govardhan Das Apt,Bldg No 796',
floor: '8nd',
roomNo: '6885'
},
isDelivered: false
}
]

Condition 2:
Here we will find all documents where customer purchased item with
item_id is 2 & quantity is 10 or more. both this condition should
be satisfied.

db.purchase.find({
cartItems:{
$elemMatch:{
item_id:{$eq:2},
quantity:{$gte:10}
}
}
})

Output:
[
{
_id: 0,
email: 'sagar@example.com',
purchaseTime: ISODate('2024-01-01T07:00:00.000Z'),
cartItems: [
{
item_id: 43,
quantity: 2,
pricePerItem: 10,
dates: {
manifacturingDate: ISODate('2023-10-10T00:00:00.000Z'),
expiryDate: ISODate('2024-04-30T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 15,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-12-10T00:00:00.000Z'),
expiryDate: ISODate('2024-06-30T00:00:00.000Z')
}
}
],
coshopper: [ 'brother', 'wife', 'sister' ],
deliveryAddress: {
city: 'Mumbai',
street: 'M k Gandhi Road',
pin: '400080',
town: 'Vikroli',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '5386'
},
isDelivered: false
}
]


Condition 3:
Find all documents where co-shopper is wife.


db.purchase.find({
coshopper:{$elemMatch:{$eq :'wife'}}
})

Output:

[
{
_id: 0,
email: 'sagar@example.com',
purchaseTime: ISODate('2024-01-01T07:00:00.000Z'),
cartItems: [
{
item_id: 43,
quantity: 2,
pricePerItem: 10,
dates: {
manifacturingDate: ISODate('2023-10-10T00:00:00.000Z'),
expiryDate: ISODate('2024-04-30T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 15,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-12-10T00:00:00.000Z'),
expiryDate: ISODate('2024-06-30T00:00:00.000Z')
}
}
],
coshopper: [ 'brother', 'wife', 'sister' ],
deliveryAddress: {
city: 'Mumbai',
street: 'M k Gandhi Road',
pin: '400080',
town: 'Vikroli',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '5386'
},
isDelivered: false
},
{
_id: 1,
email: 'swara@example.com',
purchaseTime: ISODate('2024-02-01T05:00:00.000Z'),
cartItems: [
{
item_id: 34,
quantity: 5,
pricePerItem: 20,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-20T00:00:00.000Z')
}
},
{
item_id: 56,
quantity: 5,
pricePerItem: 340,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-20T00:00:00.000Z')
}
},
{
item_id: 78,
quantity: 3,
pricePerItem: 540,
dates: {
manifacturingDate: ISODate('2023-10-25T00:00:00.000Z'),
expiryDate: ISODate('2024-08-29T00:00:00.000Z')
}
}
],
coshopper: [ 'daughter', 'wife' ],
deliveryAddress: {
city: 'Mumbai',
street: 'Indiara Gandhi Road',
pin: '400745',
town: 'Naupada',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '3276'
},
isDelivered: true,
deliveryDate: ISODate('2024-02-05T02:40:00.000Z')
},
{
_id: 3,
email: 'sachin@example.com',
purchaseTime: ISODate('2024-01-01T02:54:00.000Z'),
cartItems: [
{
item_id: 4,
quantity: 1,
pricePerItem: 23,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-01T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 1,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-10-18T00:00:00.000Z'),
expiryDate: ISODate('2024-03-20T00:00:00.000Z')
}
}
],
coshopper: [ 'wife', 'sister-in-law','daughter' ],
deliveryAddress: {
city: 'Nashik',
street: 'Jangli Maharaj Road',
pin: '2345765',
town: 'Vartak Nagar',
Bldg: 'Govardhan Das Apt,Bldg No 796',
floor: '8nd',
roomNo: '6885'
},
isDelivered: false
}
]

Condition 4:
Find all documents where atleast one item has expiry date less
than or equal to "2024-04-30"

db.purchase.find({
"cartItems.dates.expiryDate":{$lte : new Date("2024-04-30") }
})

Output:
[
{
_id: 0,
email: 'sagar@example.com',
purchaseTime: ISODate('2024-01-01T07:00:00.000Z'),
cartItems: [
{
item_id: 43,
quantity: 2,
pricePerItem: 10,
dates: {
manifacturingDate: ISODate('2023-10-10T00:00:00.000Z'),
expiryDate: ISODate('2024-04-30T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 15,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-12-10T00:00:00.000Z'),
expiryDate: ISODate('2024-06-30T00:00:00.000Z')
}
}
],
coshopper: [ 'brother', 'wife', 'sister' ],
deliveryAddress: {
city: 'Mumbai',
street: 'M k Gandhi Road',
pin: '400080',
town: 'Vikroli',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '5386'
},
isDelivered: false
},
{
_id: 3,
email: 'sachin@example.com',
purchaseTime: ISODate('2024-01-01T02:54:00.000Z'),
cartItems: [
{
item_id: 4,
quantity: 1,
pricePerItem: 23,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-01T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 1,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-10-18T00:00:00.000Z'),
expiryDate: ISODate('2024-03-20T00:00:00.000Z')
}
}
],
coshopper: [ 'wife', 'sister-in-law','daughter' ],
deliveryAddress: {
city: 'Nashik',
street: 'Jangli Maharaj Road',
pin: '2345765',
town: 'Vartak Nagar',
Bldg: 'Govardhan Das Apt,Bldg No 796',
floor: '8nd',
roomNo: '6885'
},
isDelivered: false
}
]



$all Operator:
The $all operator selects the documents where the value of a field is an array
that contains all the specified elements.

db.purchase.find({
coshopper:{$all:[ 'daughter', 'wife' ]}
})

This will gives us all douments where coshopper contain both "daughter" &
"wife" order in which this two occur is immeterial,if somewhere coshopper
contain "wife" & "daughter" and something more it will also be selected.

Output:
[
{
_id: 1,
email: 'swara@example.com',
purchaseTime: ISODate('2024-02-01T05:00:00.000Z'),
cartItems: [
{
item_id: 34,
quantity: 5,
pricePerItem: 20,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-20T00:00:00.000Z')
}
},
{
item_id: 56,
quantity: 5,
pricePerItem: 340,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-20T00:00:00.000Z')
}
},
{
item_id: 78,
quantity: 3,
pricePerItem: 540,
dates: {
manifacturingDate: ISODate('2023-10-25T00:00:00.000Z'),
expiryDate: ISODate('2024-08-29T00:00:00.000Z')
}
}
],
coshopper: [ 'daughter', 'wife' ],
deliveryAddress: {
city: 'Mumbai',
street: 'Indiara Gandhi Road',
pin: '400745',
town: 'Naupada',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '3276'
},
isDelivered: true,
deliveryDate: ISODate('2024-02-05T02:40:00.000Z')
},
{
_id: 3,
email: 'sachin@example.com',
purchaseTime: ISODate('2024-01-01T02:54:00.000Z'),
cartItems: [
{
item_id: 4,
quantity: 1,
pricePerItem: 23,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-01T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 1,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-10-18T00:00:00.000Z'),
expiryDate: ISODate('2024-03-20T00:00:00.000Z')
}
}
],
coshopper: [ 'wife', 'sister-in-law', 'daughter' ],
deliveryAddress: {
city: 'Nashik',
street: 'Jangli Maharaj Road',
pin: '2345765',
town: 'Vartak Nagar',
Bldg: 'Govardhan Das Apt,Bldg No 796',
floor: '8nd',
roomNo: '6885'
},
isDelivered: false
}
]

$size operator:

db.purchase.find({
coshopper:{$size:3}
})
This query will select all documents where coshopper array length
is exactly 3.
Output:
[
{
_id: 0,
email: 'sagar@example.com',
purchaseTime: ISODate('2024-01-01T07:00:00.000Z'),
cartItems: [
{
item_id: 43,
quantity: 2,
pricePerItem: 10,
dates: {
manifacturingDate: ISODate('2023-10-10T00:00:00.000Z'),
expiryDate: ISODate('2024-04-30T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 15,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-12-10T00:00:00.000Z'),
expiryDate: ISODate('2024-06-30T00:00:00.000Z')
}
}
],
coshopper: [ 'brother', 'wife', 'sister' ],
deliveryAddress: {
city: 'Mumbai',
street: 'M k Gandhi Road',
pin: '400080',
town: 'Vikroli',
Bldg: 'Arun Niwara,Bldg No 167',
floor: '1st',
roomNo: '5386'
},
isDelivered: false
},
{
_id: 3,
email: 'sachin@example.com',
purchaseTime: ISODate('2024-01-01T02:54:00.000Z'),
cartItems: [
{
item_id: 4,
quantity: 1,
pricePerItem: 23,
dates: {
manifacturingDate: ISODate('2023-11-05T00:00:00.000Z'),
expiryDate: ISODate('2024-07-01T00:00:00.000Z')
}
},
{
item_id: 2,
quantity: 1,
pricePerItem: 240,
dates: {
manifacturingDate: ISODate('2023-10-18T00:00:00.000Z'),
expiryDate: ISODate('2024-03-20T00:00:00.000Z')
}
}
],
coshopper: [ 'wife', 'sister-in-law', 'daughter' ],
deliveryAddress: {
city: 'Nashik',
street: 'Jangli Maharaj Road',
pin: '2345765',
town: 'Vartak Nagar',
Bldg: 'Govardhan Das Apt,Bldg No 796',
floor: '8nd',
roomNo: '6885'
},
isDelivered: false
}
]

$push operator:

The $push operator appends a specified value to an array.

db.purchase.updateOne(
{email: 'sagar@example.com'},
{ $push: { coshopper: "mother-in-law" } }
)

This will insert 'mother-in-law' to coshopper array for document
belonging to email as 'sagar@example.com'.

Here we are updationg only one document we can update multiple\
document in same way using updateMany.

db.purchase.updateMany(
{},
{ $push: { coshopper: "self" } }
)

Can we push multiple items in this co-shopper array at a time,
let us check

db.purchase.updateMany(
{},
{ $push: { coshopper: {$each:["father",'uncle'] }} }
)

yes this query pushed both father & uncle to each document in collection.

This will insert "self" into coshopper array of each document
in collection.

Suppose we want to add a free item to each cart for our customers.

db.purchase.updateMany(
{},
{ $push: { cartItems: {
item_id: 70,
quantity: 1,
pricePerItem: 25,
dates: {
manifacturingDate: ISODate('2023-10-04'),
expiryDate: ISODate('2024-08-05')
}
}
} }
)

This will push new cartItem to each cartItems array.

$sort & $slice with $push:


db.purchase.updateMany(
{},
{
$push: {
cartItems: {
$each: [
{
item_id: 0,
quantity: 1,
pricePerItem: 65,
dates: {
manifacturingDate: ISODate('2024-11-03'),
expiryDate: ISODate('2024-08-05')
}
},
{
item_id: 78,
quantity: 3,
pricePerItem: 95,
dates: {
manifacturingDate: ISODate('2023-12-07'),
expiryDate: ISODate('2024-08-05')
}
},
],
$sort: { item_id: 1 },
$slice: 2
}
}
}
)

Here in $sort: { item_id: 1 }
1 indicates ascending order (default) while -1 means descending order.

This query will first push the two cart items into cartItems array for
each document,then it sort all array elements of cartItems array based
on item_id in ascending order,then it slice the cartItems array to size 2,
so basically after this query each cartItem will have 2 elements other
get deleted.

No comments:

Post a Comment