[英]Get all documents whose property equals one of the elements in an array
I have a Post model that has a publisher
property defined in its schema (I'm using Mongoose).我有一个 Post model 在其架构中定义了publisher
者属性(我使用的是 Mongoose)。 The publisher
property is a string that refers to a publisher's name. publisher
者属性是一个引用发布者名称的字符串。
I also have an array called sourceNames
that holds all the different publisher names.我还有一个名为sourceNames
的数组,其中包含所有不同的发布者名称。 I want to query my database for ALL the posts whose publisher
matches any one of the array elements in sourceName
.我想在我的数据库中查询其publisher
者与sourceName
中的任何一个数组元素匹配的所有帖子。 My current query looks like this:我当前的查询如下所示:
const query = postModel
.find({ publisher: { $all: sourceNames } })
.limit(limit)
.skip(startIndex);
My query isn't returning anything when I exec it.当我执行它时,我的查询没有返回任何内容。 Does anyone know if what I'm trying to do is possible in a single query (Rather than loop over sourceNames
and make a query for each individual element?有谁知道我正在尝试做的事情是否可以在单个查询中进行(而不是遍历sourceNames
并为每个单独的元素进行查询?
Short短的
Just replace $all
with $in
只需将$all
替换为$in
Expl解释
$all
is trying to match an array with all elements in your array. $all
正在尝试将数组与数组中的所有元素进行匹配。
$in
instead, tries to match a string or array with one in the array. $in
相反,尝试将字符串或数组与数组中的一个匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.