查询数组大小大于1的文档 [英] Query for documents where array size is greater than 1

查看:65
本文介绍了查询数组大小大于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

1.Using $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,使用名称数组长度对其进行更新,然后在查询中使用:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆