arr=[{field1:<value1>,field2:<value2}.....]我想对arr的field1使用$in运算符。我知道我可以创建一个伪数组并将field1值推入该伪数组中。但是,有没有一种方法可以对数组的特定字段使用$in运算符?
arr数组与集合没有任何关系。
我想查询特定字段上的所有文档,这些文档的值在arr的field1中- field1应该在运算符$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字段中的文档。
查询的输出应为
[{...
fieldx:'NY',
...
},
{...
fieldx:'LA',
...
},
{...
fieldx:'NZ',
...
}]fieldx是我要查询的集合中的字段。它不是我提供的数组(arr)的字段。我希望将其与提供查询的array - arr的字段(location)进行匹配。
发布于 2014-07-01 19:04:23
您需要从输入数组中提取"location“字段,并将它们提供给$in
var locs = arr.map(function(x) { return x.location } );
db.collection.find({ "fieldx": { "$in": locs } })作为参考,我将为您重写您的问题:
我有一个包含如下文档的集合:
{ "fieldx": "NY" }
{ "fieldx": "LA" }
{ "fieldx": "SF" }我得到的是一个输入数组,其定义如下:
var arr = [
{ "name": "foo", "location": "NY"},
{ "name": "bar", "location": "LA"},
{ "name": "foobar", "location": "NZ"}
];现在,我想要编写一个查询来查找与我输入的数组中的"location“字段相匹配的所有文档。
我该怎么做呢?
我试过了:
db.collection.find({ "fieldx": { "$in": arr } })但这并不匹配。
发布于 2017-12-14 20:09:20
扩展Neil Lunn的答案,你也可以在查询中使用map函数。
var arr = [
{ "name": "foo", "location": "NY"},
{ "name": "bar", "location": "LA"},
{ "name": "foobar", "location": "NZ"}
];
db.collection.find({ "fieldx": { "$in": arr.map(function(x) { return x.location } ) } })如果您使用ES6语法,那么
db.collection.find({ "fieldx": { "$in": arr.map(x => x.location ) } })发布于 2014-07-01 14:10:17
您需要使用dot notation来选择数组中的字段:
db.coll.find({"arr.field1" : { $in : [ 'value1', 'value11' ]}});此查询将返回所有文档,其中数组arr至少包含一个子文档,该子文档的字段field1的值为value1或value11。
编辑
关于您的编辑,您不能以这种方式使用$in操作符。
$in运算符选择字段的值等于指定数组中的任意值的文档。
如果在$in查询中发送一个对象数组,它将匹配其中指定字段包含该对象的文档:
db.coll.find({ a: { $in : [ { b : 1, c: 1}, { b : 2, c: 2} ]}});您可以找到以下文档:
{
_id : ...
a: { b : 1, c: 1}
}
{
_id : ...
a: { b : 2, c: 2}
}要获得您真正想要的,最简单的查询方法是从对象数组中提取值,并使用创建的值数组进行查询。
https://stackoverflow.com/questions/24503323
复制相似问题