首页 > 解决方案 > 如何使用 Java 语法从 Mongodb 对象的嵌套数组中获取对象特定属性的值?

问题描述

我有两个 Mongodb 文档

Document 1:
{
        "_id": "456f2c293b50d15ad7b84b37",
        "system": "Maruti",
        "article": {
            "number": "123456789",
            "description": "des",
            "toy": "super"
        }
}

Document 2:
{ 
    "_id" : ObjectId("5678d3917b3d4f2a61a1a92d"), 
    "user" : "sample", 
    "Email" : "sample@gmail.com", 
    
    "Sample Systems" : [
        {
            "Car" : {
                "System" : "Maruti", 
                "indicator" : true
            }
        }, 
        {
            "Scooter" : {
                "System" : "TVS", 
                "indicator" : true
            }
        }
    ], 
 
}

我的网址是 http://localhost:8080/?system=Maruti

如果 system = Maruti ,我需要根据输入参数搜索查询,从第二个文档中我需要获取 Sample Systems.Car.System =Maruti 的指标值。在请求参数 system =TVS 的情况下,我需要取 Sample Systems.Scooter.System =TVS 的指标值。两个文档中都有很多系统动态获取基于 system 的值。我尝试使用以下逻辑没有得到想要的结果。没有从两个文档中获取逻辑来匹配系统。任何人都可以帮助我使用 Java 语法来匹配两个文档中的参数。

@RequestMapping(value = "/system", method = RequestMethod.GET)
    public Object getSystem(@RequestParam(value = "system") String system){
    MongoDatabase database = this.mongoClient.getDatabase(test);
    MongoCollection<Document> users = database.getCollection(Systems);
     List<? extends Bson> pipelinesVal = Arrays.asList(
                new Document()
                        .append("$unwind", "$Sample Systems"),
                new Document()
                        .append("$match",  new Document().append("Sample Systems","$Sample Systems")),
                new Document()
                        .append("$project", new Document()
                                .append("_id", 1)
                                .append("Systems", 1)

                        ));
        List<Document> Val = new ArrayList<>();
        List values=users.aggregate(pipelinesVal).into(Val);
        Document system =new Document();
        List<Document> aggregate = new ArrayList<>();
        
}

标签: mongodbspring-bootrest

解决方案


推荐阅读