【问题标题】:mongodb - filter query by selected value [duplicate]mongodb - 按选定值过滤查询[重复]
【发布时间】:2016-01-13 05:30:36
【问题描述】:

给定以下 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 中有一种完全不同的方式来处理它......

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    尝试使用$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}}] } )
    

    【讨论】:

    • 谢谢。答案在另一个线程上可用,但您的答案也有效,因此会将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多