我想对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针对数组对象而不是数组对象
发布评论