首页 > 解决方案 > MongoDB & Spring Boot:如何根据过滤器值从数组中仅获取特定的子文档?

问题描述

我对 MongoDB 有点陌生,并尝试使用 Spring Boot 和 Java 编写查询以仅从数组中获取匹配的子文档,但是无论我尝试如何,我都会在响应中不断获取整个文档。

我的示例数据集如下所示:

{
"storeId": "xxxxx",
"bu": "xxxxx",
"items": [
  {
    "itemId": "1234",
    "itemName": "x",
    "price": "10.0",
  },
  {
    "itemId": "43556",
    "itemName": "y",
    "price": "1.0"
  }]
}

{
"storeId": "yyyyyy",
"bu": "xxxxx",
"items": [
  {
    "itemId": "1234",
    "itemName": "x",
    "price": "0.0",
  },
  {
    "itemId": "67654",
    "itemName": "y",
    "price": "10.0"
  }]
}

我想过滤 items.itemId = 1234 和 items.price =10.0,我期待以下输出:

{
"storeId": "xxxxx",
"bu": "xxxxx",
"items": [
  {
    "itemId": "1234",
    "itemName": "x",
    "price": "10.0",
  }]
}

但是我得到

{
"storeId": "xxxxx",
"bu": "xxxxx",
"items": [
  {
    "itemId": "1234",
    "itemName": "x",
    "price": "10.0",
  }]
}

{
"storeId": "yyyyyy",
"bu": "xxxxx",
"items": [
  {
    "itemId": "1234",
    "itemName": "x",
    "price": "0.0",
  }]
}

有人可以帮我用 Spring boot 和 mongotempalte 框架编写这个查询吗?

标签: javaspringmongodbspring-boot

解决方案


推荐阅读