兼容性
可以使用 $in 查找托管在以下环境中的部署:
MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
$in 操作符采用以下形式:
{ field: { $in: [ <value1>, <value2>, ... <valueN> ] } }
关于不同 BSON 类型值的比较,请参阅指定的 BSON 比较顺序。
如果 field 有一个大量,$in操作符会选择这样的文档:其 field 的大量至少包含一个与指定大量中的值匹配的元素。示例,<value1>、<value2> 等等。
$in 将每个参数与集合中的每个文档进行比较,这可能会导致性能问题。要提高性能,请在要查询的field 上创建索引。索引允许MongoDB为每个 $in 元素创建边界并更有效地搜索。
注意
本文档介绍了$in 查询运算符。有关$in 聚合操作符,请参阅 $in(表达式操作符)。
使用MongoDB Search 在Atlas上查询数据
对于存储在MongoDB Atlas中的数据,您可以在运行 查询时使用MongoDB Search in-ref $search操作符。在$in $search之后运行 的性能低于运行带有$search in-ref操作符的 。
示例
本页上的示例使用 sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。
Match Values
此查询选择 movies 集合中 rated 字段的值为 "G" 或 "TV-G" 的文档:
db.movies.find( { rated: { $in: ["G", "TV-G"] } }, { _id: 0, title: 1 } )
[ { title: 'The Great Train Robbery' }, { title: 'A Corner in Wheat' }, { title: 'From Hand to Mouth' }, { title: 'One Week' }, { title: 'The Devil to Pay!' }, { title: 'Footlight Parade' }, { title: 'Gold Diggers of 1935' }, { title: 'Naughty Marietta' }, { title: 'Modern Times' }, { title: 'Gone with the Wind' }, { title: 'Fantasia' }, { title: 'The Man Who Came to Dinner' }, { title: 'National Velvet' }, { title: 'Alice in Wonderland' }, { title: 'The Member of the Wedding' }, { title: 'Seven Brides for Seven Brothers' }, { title: 'Around the World in Eighty Days' }, { title: 'The King and I' }, { title: 'A King in New York' }, { title: 'Ben-Hur' } ]
匹配数组中的值
当 rated 数组至少有一个与 "G" 或 "TV-G" 匹配的元素时,以下 updateMany() 操作将 familyFriendly 字段设置为 true:
db.movies.updateMany( { rated: { $in: ["G", "TV-G"] } }, { $set: { familyFriendly: true } } )
{ acknowledged: true, insertedId: null, matchedCount: 536, modifiedCount: 536, upsertedCount: 0 }
有关查询数组的其他示例,请参阅:
有关查询的其他示例,请参阅查询文档。
使用 $in 和正则表达式
$in操作符可以使用 /pattern/ 形式的正则表达式选择文档。
此查询选择 movies集合中 plot字段以 Alien 开头或包含 sci-fi 的文档:
db.movies.find( { plot: { $in: [ /^Alien/ , /sci-fi/ ] } }, { _id: 0, title: 1, plot: 1 } )
[ { plot: 'Aliens come to Earth seeking scientists to help them in their war.', title: 'This Island Earth' }, { plot: 'Censored by the Polish authorities, this film was reedited and new footage added. It begins with a sci-fi motif: abstract images and electronic music take the viewer from ruins of Lebanon ...', title: 'Rece do gèry' }, { plot: 'An idyllic sci-fi future has one major drawback: life must end at 30.', title: "Logan's Run" }, { plot: "Four horror/sci-fi segments directed by four famous directors which are their own versions of classic stories from Rod Serling's landmark television series.", title: 'Twilight Zone: The Movie' }, { plot: 'Aliens who look like clowns come from outer space and terrorize a small town.', title: 'Killer Klowns from Outer Space' }, ... ]