【问题标题】:Get inner Object list from MongoDB document with out looping.从 MongoDB 文档中获取内部对象列表,无需循环。
【发布时间】:2018-01-06 06:35:46
【问题描述】:

假设我将以下模型列表存储在 mongdb 中。

@Document
public class Product {
    private String productName;
    private List<Customer> customers;
}

public class Customer {
    public String firstName;
    List<Address> addresses;  
}

public class Address {
    private String address;
}

我有如下数据。

我想获取与以下查询相关的所有地址。

Query query = new Query();
Criteria product = Criteria.where("productName").is("CHAIR");
Criteria customer = Criteria.where("customers. firstName").is("Ann");  

我想获取不循环客户列表的上层查询的地址列表。

我正在使用弹簧数据, 所以我想知道如何通过 MatchOperation、ProjectionOperation、Aggregation 或 MapReduce 来做到这一点,而没有客户的循环列表。

【问题讨论】:

  • 不需要聚合。试试Query query = new Query(); Criteria criteria = Criteria.where("productName").is("CHAIR").and("customers.firstName").is("Ann"); query.fields().include("productName").elemMatch("customers", Criteria.where("firstName").is("Ann") );这将输出匹配名称的客户和里面的地址列表。

标签: mongodb spring-data aggregate spring-data-mongodb projection


【解决方案1】:
db.productDB.aggregate({$match:{"productName":"CHAIR"}},
{$unwind:"$customers"},{$match:{"customers.firstName":"Ann"}},{$project:{
_id:"$productName", address:"$addresses"})

请查看 mongodb 聚合框架以获取更多详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 2021-11-16
    • 2011-12-18
    相关资源
    最近更新 更多