如何在嵌套对象的 spring 数据中使用 elemMatch 从 mongodb 检索数据

How to use elemMatch in spring data for nested objects to retrieve data from mongodb

我需要一些关于在 spring 数据中使用 elemMatch 来查询 mongodb 中的数据并从 mongodb 检索结果的帮助。

我想检索特定 testRun 的结果,比如 testRun=1

我在 mongodb 中有以下数据:

[ {
"testMethod": "initialization",
"testCase": "com.harish.test.TestNGRest.OrganisationGetTest",
"build": 1,
"ranNumberofTimes": 2,
"failed": 0,
"success": 2,
"testRuns": [
  {
    "testMethod": "initialization",
    "testCase": "com.harish.test.TestNGRest.OrganisationGetTest",
    "branchName": "branch_1",
    "testRun": 1,
    "success": 1,
    "fail": 0,
    "timetorun": 0,
    "cases": [
      {
        "caseId": 1,
        "status": "success",
        "failreason": null,
        "startDate": "Fri May 27 14:41:22 EDT 2016",
        "endDate": "Fri May 27 14:41:22 EDT 2016"
      }
    ],
    "startDate": "Fri May 27 14:41:22 EDT 2016",
    "endDate": "Fri May 27 14:41:22 EDT 2016"
  },
  {
    "testMethod": "initialization",
    "testCase": "com.harish.test.TestNGRest.OrganisationGetTest",
    "branchName": "branch_1",
    "testRun": 2,
    "success": 1,
    "fail": 0,
    "timetorun": 1,
    "cases": [
      {
        "caseId": 1,
        "status": "success",
        "failreason": null,
        "startDate": "Fri May 27 14:41:49 EDT 2016",
        "endDate": "Fri May 27 14:41:49 EDT 2016"
      }
    ],
    "startDate": "Fri May 27 14:41:49 EDT 2016",
    "endDate": "Fri May 27 14:41:49 EDT 2016"
  }
]

在 mongo 控制台中,我使用了以下命令并得到了结果:

db.test.find({"testRuns.testRun":1},{"testRuns":{"$elemMatch":{"testRun":1}}}).pretty()

我在 mongo 控制台中得到了满足我要求的结果。

真正的问题来了,我在 java 代码中使用了 spring 数据来检索结果。

return mongoTemplate.find(BasicQuery.query(Criteria.where("testRuns.testRun").is(testRun).andOperator(Criteria.where("testRuns").elemMatch(Criteria.where("testRun").is(testRun)))),Test.class, COLLECTION_NAME);

但是,我无法检索特定测试的结果 运行。谁能帮我解决这个问题。

谢谢。

如果您想得到 "testRuns.testRun" = 1,则不需要 $elemMatch。没有第二个条件。请参考 mongo 参考文档中的以下声明 link.

"Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query:"

db.survey.find(
{ "results.product": "xyz" }
)

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

我已经使用下面的代码和 post 中给出的数据进行了测试。它工作正常。

请确保在 Java 代码中将 testRun 变量定义为 Integer。如果它是其他数据类型,查询将不会 return 结果。

query.addCriteria(Criteria.where("testRuns.testRun").is(testRun));
mongoOperations.find(query, Stack.class);