2015-10-14 46 views
1

篩選查詢鑑於以下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中......

回答

0

嘗試使用其中$,像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}}] }) 
+0

謝謝。答案在其他線程上可用,但您的答案也可以工作,因此將其標記爲已接受。 – lps