MongoDB:在具有多个条件的数组中查找值 [英] MongoDB : find value in Array with multiple criteria

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

问题描述

我有以下文件:

{_id : 1, numbers : [-1000, 1000]}
{_id : 2, numbers : [5]}

我试图获取一个查询,该查询将找到一个文档,该文档的numbers数组中的值介于-10和10之间(在本例中为_id:2).但是,当我尝试以下操作时:

I'm trying to get a query that will find a document that has a value in the numbers array that is between -10 and 10 (in this case, _id : 2). However, when I try the following:

db.foo.find({numbers : $and : [{$gt : -10},{$lt : 10}]})

它返回所有文档.如果没有map-reduce,这可能吗?谢谢-JWW

it returns all documents. Is this possible to do without map-reduce? Thanks, -JWW

推荐答案

您可以使用$ elemMatch来检查数组中的元素是否与指定的match表达式匹配.

You can use $elemMatch to check if an element in an array matches a specified match expression.

在这种情况下,您可以使用它来获取一个文档,该文档的数字数组的元素介于-10和10之间:

In this case, you can use it to get a document whose numbers array has an element that is between -10 and 10:

   db.foo.find( { numbers : { $elemMatch : { $gt : -10 , $lt : 10 } } } );

这只会返回_id:2文档.

This will just return the _id : 2 document.

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

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