查找所有文档的数组字段包含符合某些条件的文档

时间:2014-10-20 08:51:26

标签: json mongodb scala reactivemongo

我有一个存储所有用户数据的MongoDB集合。

我的馆藏文件有以下JSON格式:

{
    "_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
        }
    ]
}

tag字段的格式为"category:name product""tags"字段包含用户购买的所有产品。

我正在编写Scala应用程序,而我正在使用reactivemongo驱动程序。 现在我正在编写一种方法,给予categoryproduct搜索所有已购买至少一个给定类别的产品的用户,但尚未购买任何一个产品等于给定的产品

我的代码现在如下:

def findUsers(input: FindSuggestion): Future[Option[List[User]]] = {
      val category = input.category //a string
      val product = input.product  //a string, in the form category:productName
      val query = Json.obj(//create the query object)
      Users.find(query).toList.flatMap(users =>
        if(users.size > 0)
          Future{Some(users)}
        else
          Future{None}
          )
    }

为了更具体,我搜索tags字段包含tag字段以类别开头的文档的所有文档,但tags字段不包含任何文档tag == product

我怎么能在mongodb中做到这一点?

1 个答案:

答案 0 :(得分:1)

为了有效查询,您应该更改文档的结构,例如

{
    "_id" : ObjectId("542e67e07f724fc2af28ba75"),
    "id" : "",
    "email" : "luigi@gmail.com",
    "tags" : [
        {
            "category": "Fish",
            "product": "Swordfish Loin Portions"
            "weight" : 2,
            "lastInsert" : 1412327492874
        },
        {
            "category": "Vegetable",
            "product": "Carrots - Jumbo",
            "weight" : 4,
            "lastInsert" : 1412597883569
        }
    ]
}

并在类别产品

上创建索引

查询将是

$and:[{"tags.category":"requestedCategory"},{$ne:{"tags.product":"requestedProduct"}}]

如果你决定不修改结构,那么查询就是

$and:[{"tags.tag":$regex: 'requestedCategory:.*'},{$ne:{"tags.tag":"requestedCategory:requestedProduct"}}]

更新。 添加索引

db.collection.ensureIndex( { "tags.tag": 1 } )
相关问题