mongodb-按所选值筛选查询
鉴于以下mongodb文档:mongodb-按所选值筛选查询,mongodb,Mongodb,鉴于以下mongodb文档: db.customers { "name" : "customer 1", "merchants" : [ { "name" : "test merchant 1" }, { "name" : "test merchant 2" }, { "name" : "test merchant 3" } ] } { "name": "customer 2", "merchants" :
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中有一种完全不同的方式来实现它…尝试使用$where,比如 因为MongoDB只提供了
$size
操作符来检查相等性,所以可以创建一个查询,在那里检查字段是否存在,如果数组的长度不是0也不是1,这意味着大于1:
> db.customers.find( {$and: [{merchants: {$not:{$size:0}}},{merchants: {$not:{$size:1}}}, {merchants:{$exists: true}}] } )
尝试在何处使用$where,如 因为MongoDB只提供了
$size
操作符来检查相等性,所以可以创建一个查询,在那里检查字段是否存在,如果数组的长度不是0也不是1,这意味着大于1:
> db.customers.find( {$and: [{merchants: {$not:{$size:0}}},{merchants: {$not:{$size:1}}}, {merchants:{$exists: true}}] } )
非常感谢。答案在另一个线程上可用,但您的答案也有效,因此将标记为已接受。谢谢。答案在另一个线程上可用,但您的答案也有效,因此将标记为已接受。