【发布时间】:2017-07-03 07:28:23
【问题描述】:
在我的 MongoDB 数据库中,我有一个名为“recommendation.users”的集合,其中存储了所有用户数据。 我收藏的一份文件的格式如下:
{
"_id" : ObjectId("542e67e07f724fc2af28ba75"),
"id" : "",
"email" : "luigi@gmail.com",
"tags" : [
{
"tag" : "Paper Goods:Liners - Baking Cups",
"weight" : 2,
"lastInsert" : 1412327492874
},
{
"tag" : "Vegetable:Carrots - Jumbo",
"weight" : 4,
"lastInsert" : 1412597883569
},
{
"tag" : "Paper Goods:Lialberto- Baking Cups",
"weight" : 1,
"lastInsert" : 1412327548205
},
{
"tag" : "Fish:Swordfish Loin Portions",
"weight" : 3,
"lastInsert" : 1412597939124
},
{
"tag" : "Vegetable:Carrots - alberto@gmail.com",
"weight" : 2,
"lastInsert" : 1412597939124
}
]
}
作为驱动程序,我在 Scala 中使用 ReactiveMongo。
现在我正在编写一个获取tags: List[String] 的方法,并在我的集合中搜索"tags" 元素包含作为参数传递的所有值的所有用户。
换句话说,我想找到“标签”标签包含"tag" = tags(i) 的每个元素的tags 的所有文档。
如何在 MongoDB 和 reactiveMongo 中制作这样的东西??
我的方法具有以下签名:
def findUsers(tags: List[String]): Future[Option[List[User]]] = {
//search all the matching Users
//if exists at least one User return a Some(List(users))
//otherwise returns a None
}
例如,如果我的收藏中有以下两个文档:
[
{
"_id" : ObjectId("542e67e07f724fc2af28ba75"),
"id" : "",
"email" : "luigi@gmail.com",
"tags" : [
{
"tag" : "Paper Goods:Liners - Baking Cups",
"weight" : 2,
"lastInsert" : 1412327492874
},
{
"tag" : "Vegetable:Carrots - Jumbo",
"weight" : 4,
"lastInsert" : 1412597883569
},
{
"tag" : "Paper Goods:Lialberto- Baking Cups",
"weight" : 1,
"lastInsert" : 1412327548205
},
{
"tag" : "Fish:Swordfish Loin Portions",
"weight" : 3,
"lastInsert" : 1412597939124
},
{
"tag" : "Vegetable:Carrots - alberto@gmail.com",
"weight" : 2,
"lastInsert" : 1412597939124
}
]
},
{
"_id" : ObjectId("542e67e07f724fc2af28ba75"),
"id" : "",
"email" : "alberto@gmail.com",
"tags" : [
{
"tag" : "Paper Goods:Lialberto- Baking Cups",
"weight" : 1,
"lastInsert" : 1412327548205
},
{
"tag" : "Fish:Swordfish Loin Portions",
"weight" : 3,
"lastInsert" : 1412597939124
},
{
"tag" : "Vegetable:Carrots - alberto@gmail.com",
"weight" : 2,
"lastInsert" : 1412597939124
}
]
}]
如果使用 findUser(List("Fish:Swordfish Loin Portions", "Vegetable:Carrots - alberto@gmail.com")) 调用我的方法,我的方法必须返回第一个用户。
我知道可以通过检查用户是否拥有所有给定标签的循环来做到这一点,但这太复杂和冗长了。有替代品吗??
我怎样才能做到这一点??
【问题讨论】:
标签: mongodb scala reactivemongo nosql