【问题标题】:Target First Object in Array with Passed MongoDB Query使用传递的 MongoDB 查询定位数组中的第一个对象
【发布时间】:2017-09-28 20:05:57
【问题描述】:

我正在使用通过 POST 请求传递的这个 mongoDB 查询来返回数据子集:

body: any = {"services.history": { "$elemMatch": { "status": "orientation", "enrolled" : true } }};

这是按预期工作的。但是,我们正在更改我们的实现以定位状态并检查它是否是“历史”数组中的第一项。如何通过修改上述查询来完成此操作?

我认为这可能有效,但不行:

body: any = {"services.history[0]": { "$elemMatch": { "status": "orientation", "enrolled" : true } }};

我也试过点符号,还是不行:

body: any = {"services.history.0": { "$elemMatch": { "status": "orientation", "enrolled" : true } }};

如何在 POST 请求中使用这种查询仅针对数组中的第一项?换句话说,我只希望它在 elemMatch 匹配并且它是“历史”数组中的第一项时返回 true。我只需要对history 数组中的第一个对象运行此检查,因为我知道这将是后端数组中最新(最相关)的数据对象。

我查询的数据是这样的:

  "history": [
                {
                    "status": "oritentation",
                    "endDate": "2012-09-26T06:00:00.000Z",
                    "startDate": "2011-03-26T06:00:00.000Z",
                    "_id": "1259c4d250502sa434788",
                    "enrolled": true,
                }
             ]

【问题讨论】:

  • 你可以发布一些示例数据吗?

标签: javascript jquery arrays mongodb


【解决方案1】:

如果您的数组的子文档中没有其他字段,您可以这样做:

body: any = {"services.history.0": { "status": "orientation", "enrolled" : true } }

如果您确实有其他字段,您可以这样做:

body: any = { "services.history.0.status": "orientation", "services.history.0.enrolled": true }

【讨论】:

  • 我使用我的 RoboMongo 客户端运行了这两个查询,它们都为我工作......你得到什么样的语法错误?您使用的是哪个版本的 MongoDB,您使用哪种 ReST 服务来访问它?
  • 你是对的。有效!我第一次尝试时一定有错字。非常感谢,@dnickless。
猜你喜欢
  • 2020-02-29
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 2020-10-30
  • 2021-09-24
  • 1970-01-01
  • 2018-07-23
相关资源
最近更新 更多