首页 文章

CosmosDB $ elemMatch语法错误

提问于
浏览
1

对于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
        }
    ]
}

无论如何,这肯定是 not 语法错误,但没有有用的错误消息 . 如果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."
}

所以这对我也不起作用 .

1 回答

  • 0

    试试这个

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

    检查一下here

相关问题