MongoDB查找键等于数组中的字符串 [英] MongoDB find where key equals string from array

查看:75
本文介绍了MongoDB查找键等于数组中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在集合中查找所有给定键等于数组中字符串之一的文档.

I am trying to find in a collection all of the documents that have the given key equal to one of the strings in an array.

这里有一个收集的例子.

Heres an example of the collection.

{
  roomId = 'room1',
  name = 'first'
},
{
  roomId = 'room2',
  name = 'second'
},
{
  roomId = 'room3',
  name = 'third'
}

这是要浏览的数组的示例.

And heres an example of the array to look through.

[ 'room2', 'room3' ]

我认为可行的是...

What i thought would work is...

collection.find({ roomId : { $in : [ 'room2', 'room3' ]}}, function( e, r )
{
  // r should return the second and third room
});

我该如何实现?

解决这个问题的一种方法是做一个for循环...

One way this could be solve would be to do a for loop...

var roomIds = [ 'room2', 'room3' ];
for ( var i=0; i < roomIds.length; i++ )
{
  collection.find({ id : roomIds[ i ]})
}

但这并不理想....

推荐答案

您发布的内容应该可以运行-无需循环. $in 运算符可完成此工作:

What you posted should work - no looping required. The $in operator does the job:

> db.Room.insert({ "_id" : 1, name: 'first'});
> db.Room.insert({ "_id" : 2, name: 'second'});
> db.Room.insert({ "_id" : 3, name: 'third'});
> // test w/ int
> db.Room.find({ "_id" : { $in : [1, 2] }});
{ "_id" : 1, "name" : "first" }
{ "_id" : 2, "name" : "second" }
> // test w/ strings
> db.Room.find({ "name" : { $in : ['first', 'third'] }});
{ "_id" : 1, "name" : "first" }
{ "_id" : 3, "name" : "third" }

这不是您所期望的吗?

经过MongoDB 2.1.1的测试

Tested w/ MongoDB 2.1.1

这篇关于MongoDB查找键等于数组中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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