如何查询:aggregate。$ match - > $ lookup - >其中x = 11

时间:2017-01-12 17:36:09

标签: mongodb mongodb-query aggregation-framework

我有两个mongo集合,它们是关系:

contacts_collecion

{ "contact_id" : "1", "e" : "a1@a.aaa" }
{ "contact_id" : "2", "e" : "a2@a.aaa" }
{ "contact_id" : "3", "e" : "a3@a.aaa" }
...
...

contacts_groups_collection

{ "contact_id" : "2", "group_id" : "1"  }
{ "contact_id" : "3", "group_id" : "1"  }
{ "contact_id" : "3", "group_id" : "2"  }
...
...

如此典型的多对多关系 - 我还有一个groups_collection。每个联系人都可以分为多个小组。

当我查询时: db.contacts.aggregate([{ "$match" : { "a" : false, "e" : /ab/ } }, { "$lookup" : { "from" : "contacts_groups", "localField" : "contact_id", "foreignField" : "contact_id", "as" : "details" } }])

我明白了:

1) { "contact_id" : "1", "e" : "abcd@gmail.com", "details" : [{ "contact_id" : "1", "group_id" : "1" }, { "contact_id" : "1", "group_id" : "2" }] }
2) { "contact_id" : "2", "e" : "abcdef@gmail.com", "details" : [{ "contact_id" : "2", "group_id" : "2" }, { "contact_id" : "2", "group_id" : "3" }] }
3) { "contact_id" : "3", "e" : "abcdefgh@gmail.com", "details" : [] }

但我想只获得第二行(2),所以只有那些“group_id”:“3”。 我怎样才能做到这一点?
我这样做的方式是“加入和最有效”吗?

0 个答案:

没有答案