使用Java驱动程序针对mongodb从集合中获取数组字段

时间:2018-10-09 18:20:17

标签: arrays json mongodb collections

尝试将特定的MongoDB字段提取为数组时遇到问题。因此,我有一个名为“用户”的集合,并在名为“项”的字段中的用户中嵌套了数据,如下所示:

{ "_id" : "1", "username" : "apacheuser", "password" : "Summer95!", "firm" : "apache", "roles" : [ "client,admin" ], "items" : [ { "_id" : "12323", "item-id" : "12312", "item-name" : "İtemic", "price" : 123123, "quantity" : 1231231 }, { "_id" : "123123", "item-id" : "12313", "item-name" : "aftereror", "price" : 1232, "quantity" : 12313213 } ] }
{ "_id" : "2", "username" : "springuser", "password" : "Spring99!", "firm" : "SpringSource", "roles" : [ "client" ], "items" : [ { "_id" : "01231q", "item-id" : "1233", "item-name" : "Patates", "price" : 12321, "quantity" : 12 } ] }
{ "_id" : "3", "username" : "user3", "password" : "Autumn03!", "firm" : "RedHat", "roles" : [ "client" ] }

使用以下查询,我可以获取所需的字段,但是,对于JSON解析,我需要从查询结果中删除items标记。

Bson bsonFilter = Filters.eq("username", "apacheuser");
List<Document> results =db.getCollection("users").find(bsonFilter).projection(fields(include("items"),excludeId()))

预期结果是这样

[ { "_id" : "12323", "item-id" : "12312", "item-name" : "İtemic", "price" : 123123, "quantity" : 1231231 }, { "_id" : "123123", "item-id" : "12313", "item-name" : "aftereror", "price" : 1232, "quantity" : 12313213 } ] }

相反,我得到了:

"items" : [{ "_id" : "12323", "item-id" : "12312", "item-name" : "İtemic", "price" : 123123.0, "quantity" : 1231231 }, { "_id" : "123123", "item-id" : "12313", "item-name" : "aftereror", "price" : 1232.0, "quantity" : 12313213 }] }

因此,很明显,我只需要删除'items'标记即可正确解析。但是我对如何做到这一点感到困惑。

0 个答案:

没有答案