首页 > 解决方案 > CosmosDB $elemMatch 语法错误

问题描述

对于 CosmosDB 的 MongoDB API 中的某些命令,我​​收到一个奇怪的语法错误。假设我有一个名为“Collection”的集合,其中包含两个文档:

{
    "_id" : 1,
    "arr" : [
        {
            "_id" : 11
        },
        {
            "_id" : 12
        }
    ]
}

{
    "_id" : 2,
    "arr" : [
        {
            "_id" : 21
        },
        {
            "_id" : 22
        }
    ]
}

如果我尝试运行查询

db.getCollection('Collection').find( { _id : 2 }, { arr : { $elemMatch : { _id : 21 } } })

我得到结果

{
    "_t" : "OKMongoResponse",
    "ok" : 0,
    "code" : 9,
    "errmsg" : "Syntax error, incorrect syntax near '10'.",
    "$err" : "Syntax error, incorrect syntax near '10'."
}

但是该命令在我本地托管的 MongoDB 实例上运行良好,返回了预期的结果:

{
    "_id" : 2,
    "arr" : [ 
        {
            "_id" : 21
        }
    ]
}

无论如何,这肯定不是语法错误,但没有任何有用的错误信息。如果 CosmosDB 尚不支持这一点,有没有办法只获取存储在数组中的某些嵌入式文档?

如果我尝试使用聚合管道仅提取数组中的文档(我意识到这应该给出与上面的命令不同的结果,但它也适用于我的目的),如下所示:

db.getCollection('Collection').aggregate([{ "$unwind" : "$arr" }, { "$match" : { "arr._id" : 21 } }] )

我得到结果

{
    "_t" : "OKMongoResponse",
    "ok" : 0,
    "code" : 118,
    "errmsg" : "$match is currently only supported when it is the first and only stage of the aggregation pipeline. Please restructure your query to combine multiple $match stages into a single $match stage.",
    "$err" : "$match is currently only supported when it is the first and only stage of the aggregation pipeline. Please restructure your query to combine multiple $match stages into a single $match stage."
}

所以这对我也不起作用。

标签: azure-cosmosdbazure-cosmosdb-mongoapi

解决方案


试试这个

db.collection.aggregate([
  {
    $match: {
      "_id": 2
    }
  },
  {
    $project: {
      arr: {
        $filter: {
          input: "$arr",
          as: "ar",
          cond: {
            $eq: [
              "$$ar._id",
              21
            ]
          }
        }
      }
    }
  }
])

在这里检查


推荐阅读