用户,我有一个问题,我会感谢您的帮助。
我有三个mongo集合,它们的行为与关系数据库表中的相似:
contacts_collecion
{
"_id" : ObjectId("..."),
"cid" : "1",
"email" : "a1@a.aaa"
}
{
"_id" : ObjectId("..."),
"cid" : "2",
"email" : "a2@a.aaa"
}
{
"_id" : ObjectId("..."),
"cid" : "3",
"email" : "a3@a.aaa"
}groups_collection
{
"_id" : ObjectId("..."),
"gid" : "1",
"group_name" : "group1"
}
{
"_id" : ObjectId("..."),
"gid" : "1",
"group_name" : "group2"
}contacts_groups_collection
{
"_id" : ObjectId("..."),
"cid" : "2",
"gid" : "1"
}
{
"_id" : ObjectId("..."),
"cid" : "3",
"gid" : "1"
}
{
"_id" : ObjectId("..."),
"cid" : "3",
"gid" : "2"
}所以我对很多人的关系-每一个接触都可以在每一组。I希望使用sql的mongo等效项查询mongodb。
SELECT contacts.*
FROM dbo.contacts INNER JOIN dbo.contacts_groups ON dbo.contacts.cid = dbo.contacts_groups.cid
WHERE dbo.contacts.email LIKE '%a%' AND dbo.contacts_groups.gid = '1'
ORDER BY dbo.contacts.email1)我知道如何构建第一个过滤器(WHERE dbo.contacts.email LIKE '%a%')。
db.contacts.find({"email": /a/})使用"C#/.NET驱动程序版本2.3“,我可以使用它(我还需要分页,所以我有:
FilterDefinition<ContactSerial> filter = Builders<ContactSerial>.Filter.Regex("Email", "aaa");
List<ContactSerial> contactsList = m_mongoConn.ContactsColl.Find(filter).Skip(0).Limit(5).ToList();2)我认为如何实现内部连接的等效(不理想)(即使mongo不是关系db)。
我找到了一个$lookup:db.contacts.aggregate([{ $lookup: {from: "contacts_groups", localField: "cid", foreignField: "cid", "as": "details"}}])
使用"C#/.NET驱动程序版本2.3":mongoConn.ContactsColl.Aggregate().Lookup("contacts_groups", "cid", "cid", "details");
$lookup会给我
{
"_id" : ObjectId("..."),
"cid" : "1",
"email" : "a1@a.aaa",
"details" : [ ]
}
{
"_id" : ObjectId("..."),
"cid" : "2",
"email" : "a2@a.aaa",
"details" : [
{
"_id" : ObjectId("..."),
"cid" : "2",
"gid" : "1"
}
]
}
{
"_id" : ObjectId("..."),
"cid" : "3",
"email" : "a3@a.aaa",
"details" : [
{
"_id" : ObjectId("..."),
"cid" : "3",
"gid" : "1"
},
{
"_id" : ObjectId("..."),
"cid" : "3",
"gid" : "2"
}
]
}我的问题是:
a)如何将正则表达式过滤器(1)与$lookup (2)组合在一个MongoShell查询中?
如何使用"C#/.NET驱动程序版本2.3"进行此操作
b)如何在MongoShell查询中添加第二个筛选器(AND dbo.contacts_groups.group_id = '1') --注意这是来自第二个集合: contacts_gropups而不是contacts
如何在"C#/.NET驱动程序版本2.3"中?
c)如何在所有这些中添加a (ORDER BY dbo.contacts.email)
发布于 2017-01-15 10:59:54
1)若要为聚合查询预先筛选值,请使用match:
db.contacts.aggregate([
{$match:{email: {"$regex":/a/}}},
{$lookup: {from: "contacts_groups", localField: "cid", foreignField: "cid", "as": "details"}}])您还可以使用预定义的过滤器在c#中进行聚合:
m_mongoConn.ContactsColl
.Aggregate()
.Match(filter)
.Lookup("contacts_groups", "cid", "cid", "details")2)您需要在查找之后执行另一个项目。参见这里的一个示例:滤波$lookup结果
3)在聚合流水线中对输出进行排序,可以使用Sort。注意,在您的聚合中,您可以从Contacts获得Match,但是在Lookup之后只有Bson。因此,最好在Match和Lookup之间进行排序。
m_mongoConn.ContactsColl
.Aggregate()
.Match(filter)
.Sort(Builders<ContactSerial>.Sort.Ascending(c=>c.email))
.Lookup("contacts_groups", "cid", "cid", "details")https://stackoverflow.com/questions/41602123
复制相似问题