查询数组大小大于 1 的文档 [英] Query for documents where array size is greater than 1
问题描述
我有一个包含以下格式文档的 MongoDB 集合:
I have a MongoDB collection with documents in the following format:
{
"_id" : ObjectId("4e8ae86d08101908e1000001"),
"name" : ["Name"],
"zipcode" : ["2223"]
}
{
"_id" : ObjectId("4e8ae86d08101908e1000002"),
"name" : ["Another ", "Name"],
"zipcode" : ["2224"]
}
我目前可以获取匹配特定数组大小的文档:
I can currently get documents that match a specific array size:
db.accommodations.find({ name : { $size : 2 }})
这会正确返回 name
数组中包含 2 个元素的文档.但是,我无法执行 $gt
命令来返回 name
字段的数组大小大于 2 的所有文档:
This correctly returns the documents with 2 elements in the name
array. However, I can't do a $gt
command to return all documents where the name
field has an array size of greater than 2:
db.accommodations.find({ name : { $size: { $gt : 1 } }})
如何选择name
数组的大小大于1的所有文档(最好无需修改当前数据结构)?
How can I select all documents with a name
array of a size greater than one (preferably without having to modify the current data structure)?
推荐答案
更新:
对于 mongodb 版本 2.2+,@JohnnyHK 在另一个 回答.
For mongodb versions 2.2+ more efficient way to do this described by @JohnnyHK in another answer.
1.使用$where>
db.accommodations.find( { $where: "this.name.length > 1" } );
可是……
Javascript 的执行速度比上面列出的本机运算符慢这个页面,但是很灵活.查看服务器端处理页面了解更多信息.
Javascript executes more slowly than the native operators listed on this page, but is very flexible. See the server-side processing page for more information.
2.创建extra字段NamesArrayLength
,用names数组长度更新它,然后在查询中使用:
2.Create extra field NamesArrayLength
, update it with names array length and then use in queries:
db.accommodations.find({"NamesArrayLength": {$gt: 1} });
这将是更好的解决方案,并且运行速度会更快(您可以在其上创建索引).
It will be better solution, and will work much faster (you can create index on it).
这篇关于查询数组大小大于 1 的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!