Mongodb $ in针对数组对象而不是数组对象 [英] Mongodb $in against a field of objects of array instead of objects of array
问题描述
arr=[{field1:<value1>,field2:<value2}.....]
我想对arr
的field1
使用$in
运算符.我知道我可以创建一个虚拟数组并在虚拟数组中推送field1
值.但是,有没有一种方法可以对数组的特定字段使用$in
运算符?
I want to use the $in
operator against the field1
of arr
. I know I could create a dummy array and push the field1
values in the dummy array. But is there a way to use the $in
operator against a particular field of an array?
arr
数组与集合无关.
我想查询其值在arr
的field1
中的特定字段上的所有文档-field1应该在运算符$in
的右侧
I want to query all the documents on a particular field whose value is in the field1
of arr
- field1 should be in the right hand side of operator $in
示例:
arr=[{name:'foo',location:'NY'},{name:'bar',location:'LA'},{name:'foobar',location:'NZ'}]
db.collection.find({fieldx:<Here I want some method to obtain all documents whose fieldx values are in the location field of arr>})
输出中应该包含fieldx
值出现在arr
的location
字段中的文档.
The output should contain documents whose fieldx
values are present in the location
field of arr
.
查询的输出应该是
[{...
fieldx:'NY',
...
},
{...
fieldx:'LA',
...
},
{...
fieldx:'NZ',
...
}]
fieldx
是我要查询的集合中的字段.它不是我要提供的数组的字段(arr
).我想将其匹配到数组的字段(location
)-arr
我正在提供查询.
fieldx
is the field in the collection I am querying on. It is not a field of the array I'm providing(arr
). I want to match this to a field(location
) of array - arr
I'm providing the query.
推荐答案
您需要从输入数组中提取位置"字段,并将其提供给 $in
:
You need to extract the "location" fields from your input array and feed them to $in
:
var locs = arr.map(function(x) { return x.location } );
db.collection.find({ "fieldx": { "$in": locs } })
在这里作为参考,我将为您重新编写您的问题:
For reference here I'm going to re-write your question for you:
我有一个包含如下文档的集合:
I have a collection that contains documents like this:
{ "fieldx": "NY" }
{ "fieldx": "LA" }
{ "fieldx": "SF" }
我所拥有的是一个定义如下的输入数组:
What I have is an input array that is defined like this:
var arr = [
{ "name": "foo", "location": "NY"},
{ "name": "bar", "location": "LA"},
{ "name": "foobar", "location": "NZ"}
];
现在,我想编写一个查询来查找与我要输入的数组中的位置"字段相匹配的所有文档.
Now I want to write a query to find all the documents that match the "location" field in the array I have for input.
我该怎么做?
我尝试过:
db.collection.find({ "fieldx": { "$in": arr } })
但这不匹配.
这篇关于Mongodb $ in针对数组对象而不是数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!