Javascript 使用传递的MongoDB查询将数组中的第一个对象作为目标
我使用通过POST请求传递的mongoDB查询返回数据子集:Javascript 使用传递的MongoDB查询将数组中的第一个对象作为目标,javascript,jquery,arrays,mongodb,Javascript,Jquery,Arrays,Mongodb,我使用通过POST请求传递的mongoDB查询返回数据子集: body: any = {"services.history": { "$elemMatch": { "status": "orientation", "enrolled" : true } }}; 这是预期的工作。但是,我们正在将实现更改为目标状态,并检查它是否是“历史”数组中的第一项。我如何通过修改上述查询来实现这一点 我想这可能行得通,但不行: body: any = {"services.history[0]": { "$e
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匹配并且它是“history”数组中的第一项时返回true。我只需要对history
数组中的第一个对象运行此检查,因为我知道这将是后端数组中最新(最相关)的数据对象
我查询的数据如下所示:
"history": [
{
"status": "oritentation",
"endDate": "2012-09-26T06:00:00.000Z",
"startDate": "2011-03-26T06:00:00.000Z",
"_id": "1259c4d250502sa434788",
"enrolled": true,
}
]
如果数组的子文档中没有其他字段,则可以执行以下操作:
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。