MongoDB:在数组匹配参数中查找子文档 [英] MongoDB: Find Subdocument in Array Matching Parameters

查看:116
本文介绍了MongoDB:在数组匹配参数中查找子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中,我想根据满足某些参数的子文档的值查找文档.具体来说,我有一个结构如下的文件:

In MongoDB I would like to find a document based on the values of a subdocument meeting certain parameters. Specifically I have a document structured like this:

{
  name: "test",
  data: [{
    name: "test1",
    start: 0,
    end: 2
  },
  {
    name: "test2",
    start: 15
    end: 18
  }]
}

如果数据子文档的开始时间小于5,而同一子文档的结束时间大于5,我如何告诉MongoDB仅返回我的文档?目前,如果我这样做

How can I tell MongoDB to only return my document if the start time for a data subdocument is less than 5 and the end time for the same subdocument is greater than 5? Currently, if I do

db.foo.findOne({
  'data.start': { $lte: 5 },
  'data.end': { $gte: 5 }
})

它将始终返回我的文档,因为5大于0且小于18.我如何告诉MongoDB仅在5(或任何值)大于0且小于2或大于15且仅返回5时才返回我的文档.小于18?

it will return my document always because 5 is greater than 0 and less than 18. How can I tell MongoDB to only return my document if 5 (or whatever value) is greater than 0 and less than 2 OR greater than 15 and less than 18?

推荐答案

您要使用 $ elemMatch .

db.foo.findOne({ data: { $elemMatch : {
  start: { $lte: 5 },
  end: { $gte: 5 }
  }}
})

这篇关于MongoDB:在数组匹配参数中查找子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆