英文:
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: [{ "field_name": "state" },{ "field_name": "last_name" },{ "field_name": "first_name" }] } })
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论