Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (4k points)

Given the following mongodb documents:

db.customers
{
    "name" : "customer 1",
    "merchants" : [
        { "name" : "test merchant 1" },
        { "name" : "test merchant 2" },
        { "name" : "test merchant 3" }
    ]
}
{
    "name": "customer 2",
    "merchants" : [
        { "name" : "test merchant 1" }
    ]
}

How would I do a find and return only the customer with more than one merchant.

Coming from a SQL background, the equivalent would be:

Customers Table:
id int(11),
name char(56)

Merchants Table:
name char(56),
customer_id int(11)

select customer.id, count(merchants.id) as m_count 
from 
customers, merchants 
where
customers.id = merchants.customer_id
group by
customers.id
having
m_count > 1;

How would I accomplish this in mongodb? I've gotten as far as using an aggregate to get the count of merchants, but don't know how to filter the results based on the count. Maybe there's a whole different way to go about it in mongodb...

1 Answer

0 votes
by (8.7k points)

This can be easily achieved by using $where as:

 db.customers.find( { $where: "this.merchants.length > 1" } )

MongoDB provides a $size operator only to check equality and also allows individuals to create a query that will help in checking whether a certain field exists or checking the length of the array is bigger than 1 or not.

db.customers.find( {$and: [{merchants: {$not:{$size:0}}},{merchants: {$not:{$size:1}}}, {merchants:{$exists: true}}] } )

Related questions

0 votes
1 answer
asked Feb 19, 2021 in Web Technology by adhiraj (4k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...