简体   繁体   English

获取其属性等于数组中元素之一的所有文档

[英]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.

相关问题 猫鼬-查找其数组属性包含给定子集的所有文档? - Mongoose - find all documents whose array property contains a given subset? 如何在文档中查找包含数组中所有元素的文档? - how to find documents with all elements in the array in the document? 在集合中的所有文档中获取与特定数组元素内容匹配的数组元素 - Get array elements across all documents in the collection that match a specific array element content 如何查询数组字段至少有一个属性等于'X'的对象元素的所有文档? - How to query all documents where array field have at least one object-element with property equal 'X'? 在一个数组中获取所有数组元素mongodb + node.js - Get all array elements in one array mongodb + node.js 创建所有 N 位数字的数组,其数字之和等于 S - Create array of all N digit numbers whose sum of digit equals S 如何获取具有非唯一数组元素的文档? - How to get documents with non unique array elements? 如何检索其属性是给定参数的子字符串的所有文档? - How can I retrieve all documents whose property is a substring of a given parameter? MongoDB获取具有至少一个非空数组的文档 - MongoDB get documents with at least one not empty array 使用 Mongoose 中另一个 model 的属性查找一个 model 中的所有文档 - Find all documents in one model using property of another model in Mongoose
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM