MongoDB - 查找元素,其中字段在数组中至少等于一个值

时间:2016-03-15 12:24:16

标签: javascript arrays mongodb

我已经"反向"问题经典"在数组中找到值"。

我得到了一组id,我想找到元素,这个元素在这个数组中有值。

示例:

我在MyCollection中有这个

{a: 10}
{a: 7}
{a: 6}
{a: 15}

我想做这样的查询

MyCollection.find({a: [6,15])

哪会让我回头

[
    {a: 6},
    {a: 15}
]

2 个答案:

答案 0 :(得分:2)

请尝试使用$in

> db.testdata.find({a: {$in: [6, 15]}})

使用数据

> db.testdata.find()
{ "_id" : ObjectId("56e800e2abc8519548297bc3"), "a" : 10 }
{ "_id" : ObjectId("56e800e5abc8519548297bc4"), "a" : 6 }
{ "_id" : ObjectId("56e800eaabc8519548297bc5"), "a" : 15 }

测试代码

> db.testdata.find({a: {$in: [6, 15]}})
{ "_id" : ObjectId("56e800e5abc8519548297bc4"), "a" : 6 }
{ "_id" : ObjectId("56e800eaabc8519548297bc5"), "a" : 15 }

答案 1 :(得分:-1)

您可以$gte - 更高和lt - 小于

db.collection.find({ "a" : { $gte: 6, $lte: 15} } );  
相关问题