【问题标题】:Spring Data with mongodb query to bring some elements from the arraySpring Data 与 mongodb 查询以从数组中获取一些元素
【发布时间】:2020-04-21 18:19:20
【问题描述】:

我试图将数组中的多个项目放入一个对象中,但结果只是该数组中的一个项目。我想要的是从这个数组中带几个项目。

我有:

{
"title": "market",
"products": [
             {"name": "pepperoni pizza"},
             {"name": "mozzarella pizza"},
             {"name": "yogurt"},
             {"name": "soda"},
            ] 
}

还有:

Query query = new Query();
        query.fields().elemMatch("products", Criteria.where("name").regex("pizza", "i"))
                .include("products")
                .include("title");
        mongoTemplate.find(query, Business.class);

结果:

{
"title": "market",
"products": [
             {"name": "pepperoni pizza"}
            ] 
}

但我想要:

{
"title": "market",
"products": [
             {"name": "pepperoni pizza"},
             {"name": "mozzarella pizza"}
            ] 
}

【问题讨论】:

  • 查询的行为符合预期。这是因为您使用的是 $elemMatch 投影运算符。根据定义,它将查询结果中的数组字段的内容限制为仅包含匹配$elemMatch 条件的第一个元素。要过滤您期望的方式,您必须使用带有 $filter 的聚合查询。

标签: java mongodb spring-boot spring-data


【解决方案1】:

无法使用 spring 数据版本,但这是它应该生成的 mongo 查询:

db.collection.aggregate([
    {
        $match: {
            'products.name': /pizza/i
        }
    },
    {
        $set: {
            products: {
                $filter: {
                    input: "$products",
                    cond: { $regexMatch: { input: "$$this.name", regex: /pizza/i } }
                }
            }
        }
    }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2020-10-07
    • 1970-01-01
    • 2020-06-01
    • 2021-05-06
    相关资源
    最近更新 更多