查找包含给定数组中所有值的集合中的记录。

huangapple go评论66阅读模式
英文:

finds records in a collection that contains all values in a given array

问题

MongoDB 中是否有一个函数可以查找集合中包含给定数组中所有值的记录?
例如:
我有一个名为 channels 的集合,
该集合有一个名为 fields 的字段。字段 fields 包含一个对象数组。
示例:

{
  "_id": "1advs23rfwdfsd23r32r2wf89UJ*ADJ8j10u9u1-2u3",
  "fields": [
     {
      "field_name": "first_name"
     },
     {
      "field_name": "last_name"
     },
    ]
 }

是否有一个函数可以查找所有包含特定字段集的 Channels?
例如:
查找所有包含字段 "first_name", "last_name", "state" 的 channels。

我尝试了以下方法,但没有成功:

Channel.find({ fields: { $all: [{ "field_name": "state" },{ "field_name": "last_name" },{ "field_name": "first_name" }] } })
英文:

is there a function in mongodb that finds records in a collection that contains all values in a given array?
ex:
i have a collection called channels,
the collection has a field called fields. The field fields contains an array of objects.
example:

{
  _id: "1advs23rfwdfsd23r32r2wf89UJ*ADJ8j10u9u1-2u3",
  fields:[
     {
      "field_name": "first_name"
     },
     {
      "field_name": "last_name"
     },
    ]
 }

is there a function that can find all the Channels that contain a certain set of fields?
example:
find all the channels that contain the fields :"first_name", "last_name", "state".

I tried the following but it didnt work

Channel.find({ fields: { $all: [{ "field_name": "state" },{ "field_name": "last_name" },{ "field_name": "first_name" }] } })

答案1

得分: 0

$in 用于选择字段的值等于数组中给定值之一的文档,并且只有当所有值与文档中的数组字段的值匹配时,$all 才起作用。

Channel.find({ fields: { $in: [{ "field_name": "state" },{ "field_name": "last_name" },{ "field_name": "first_name" }] } })
英文:

Use $in

It is used to select documents in which the field's value equals any of the given values in the array

and $all will work only if all the values match the values of an array field in a document

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

Channel.find({ fields: { $in: [{ &quot;field_name&quot;: &quot;state&quot; },{ &quot;field_name&quot;: &quot;last_name&quot; },{ &quot;field_name&quot;: &quot;first_name&quot; }] } })

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月10日 10:59:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75065019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定