MongoDB $match by 数组子集

标签 mongodb match

在MongoDB中存储对象的形式为

{ array: ["a", "b", "c", ... ] }
{ array: ["a", "d", "f", ... ] }
...

我想检索所有具有例如"b" "d" 作为其 array 字段中的值。我怎样才能做到这一点?我尝试的是

{ $match: { array: { $all: [ "b", "d" ] } } }

但这需要 "b" "d" 存在才能匹配。

最佳答案

您可以使用 $or 运算符对 array 字段进行简单查询,或者使用 $in 操作,如下 Sammaye 指出的那样(这将提高性能) :

http://docs.mongodb.org/manual/reference/operator/or/#op._S_or

> db.coll.insert({ array: ["a", "b", "c"] })
> db.coll.insert({ array: ["a", "d", "f"] })
>
> db.coll.find({ array : 'b' })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
>
> db.coll.find({ array : 'a' })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("51cc7ab481e227fe57ccb56a"), "array" : [ "a", "d", "f" ] }

$在:

> db.coll.find({ array : { $in : ['a', 'b'] } })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("51cc7ab481e227fe57ccb56a"), "array" : [ "a", "d", "f" ] }

> db.coll.find({ array : { $in : ['c', 'z'] } }) 
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }

$或:

> db.coll.find({ $or : [ { array  : 'a' }, { array : 'b' } ] })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("51cc7ab481e227fe57ccb56a"), "array" : [ "a", "d", "f" ] }
>
> db.coll.find({ $or : [ { array  : 'c' }, { array : 'z' } ] })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }

如果在数组字段上添加索引,这些查询将会更快。

关于MongoDB $match by 数组子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349825/

相关文章:

javascript - 如何最高效地更新MongoDB中的大量文档?

node.js - ElasticSearch 多字段搜索查询

java在Mongo中创建并启动存储过程?

java - 如何在 spring-data-mongodb 中使用 mongodb 日期函数运行 mongodb native 查询?

php - mysql AND语句

javascript - 使用 .match() 返回未定义的 0

node.js - Mongo +检查存在的多个字段

excel - 如何在excel中从不同列的列表中找到正确的ID号以与正确的单元格进行比较

mysql - 将文章标题与另一个表中列出的标签相匹配

javascript - .match 数组值未定义