mongodb - 按选定值

时间:2015-10-14 22:50:30

标签: mongodb

鉴于以下mongodb文件:

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" }
    ]
}

我如何查找并仅返回有多个商家的客户。

来自SQL背景,等效的是:

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;

我如何在mongodb中实现这一目标?我已经使用聚合来获得商家的数量,但不知道如何根据计数过滤结果。也许在mongodb中有一种完全不同的方式......

1 个答案:

答案 0 :(得分:0)

尝试使用$ where,例如here

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

因为MongoDB只提供$size运算符来检查是否相等,所以可以创建一个查询,在哪里检查字段是否存在,如果数组的长度不是0而不是1,则意味着大于1:

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