I have a db like this
[
{
_id: ObjectId("1"),
name: "John Doe",
age: 25,
address: {
street: "123 Main St",
city: "New York",
state: "NY",
zip: "10001"
},
images : [
{
url: "http://www.example.com/image1.jpg",
caption: "Image 1"
type: "jpg"
},
{
url: "http://www.example.com/image2.jpg",
caption: "Image 2"
type: "png"
},
{
url: "http://www.example.com/image3.jpg",
caption: "Image 3"
type: "svg"
},
{
url: "http://www.example.com/image4.jpg",
caption: "Image 4"
type: "jpg"
}
]
},
{
_id: ObjectId("2"),
name: "Jack",
age: 22,
address: {
street: "132 lake",
city: "New York",
state: "NY",
zip: "10001"
},
images : [
{
url: "http://www.example.com/image212.jpg",
caption: "Image 212"
type: "png"
},
{
url: "http://www.example.com/image34.jpg",
caption: "Image 34"
type: "svg"
}
]
},
{
_id: ObjectId("3"),
name: "Random name",
age: 27,
address: {
street: "Lajpat nagar",
city: "New Delhi",
state: "Delhi",
zip: "121002"
},
images : [
{
url: "http://www.example.com/image5.jpg",
caption: "Image 5"
type: "jpg"
},
{
url: "http://www.example.com/image7.jpg",
caption: "Image 7"
type: "png"
},
{
url: "http://www.example.com/image12.jpg",
caption: "Image 12"
type: "svg"
},
{
url: "http://www.example.com/image8.jpg",
caption: "Image 8"
type: "jpg"
}
]
}
]
I want to calculate total number of records in which images array has more than one ‘jpg’ type image object in them.
For above DB it should be 2
i.e. for Object Id 1 & 2.
As in 1, there are 2 objects in the images array with type ‘jpg’.
There are no such objects in Record 2.
While the 3rd Record also have 2 such objects.
How to do query in mongoDB, I have tried using $size & $unwind & $group operator but failed to do it.
2
Answers
you could do something as follows :
See on mongoplayground https://mongoplayground.net/p/LCCcCNkyzZX
What i do here is a
$match
to get all document where length ofimages
(filtered bytype = jpg
) is>=2
.Then i use the
$count
operator to retrieve the number of document matched previously.I think I have a solution for you. I have used
$unwind
,$match
,$group
and$sum
. Here is my code below =>Code
Update
Check the link: https://mongoplayground.net/p/lHDjL_25tyT
Output
Note: Please check the link : https://mongoplayground.net/p/zVi4MlOc-Fs