mongodb 查询数组大小大于 1 的文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7811163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:16:42  来源:igfitidea点击:

Query for documents where array size is greater than 1

mongodbmongodb-query

提问by emson

I have a MongoDB collection with documents in the following format:

我有一个包含以下格式文档的 MongoDB 集合:

{
  "_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 }})

This correctly returns the documents with 2 elements in the namearray. However, I can't do a $gtcommand to return all documents where the namefield has an array size of greater than 2:

这将正确返回name数组中包含 2 个元素的文档。但是,我无法执行$gt命令来返回该name字段的数组大小大于 2 的所有文档:

db.accommodations.find({ name : { $size: { $gt : 1 } }})

How can I select all documents with a namearray of a size greater than one (preferably without having to modify the current data structure)?

如何选择name大小大于 1的数组的所有文档(最好无需修改当前数据结构)?

采纳答案by Andrew Orsich

Update:

更新:

For mongodb versions 2.2+more efficient way to do this described by @JohnnyHKin another answer.

MongoDB的版本2.2+更有效的方式来做到这一点的描述@JohnnyHK在另一个答案



1.Using $where

1.使用$where

db.accommodations.find( { $where: "this.name.length > 1" } );

But...

但...

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.

Javascript 的执行速度比此页面上列出的本机运算符慢,但非常灵活。有关更多信息,请参阅服务器端处理页面。

2.Create extrafield NamesArrayLength, update it with names array length and then use in queries:

2.创建额外的字段NamesArrayLength,用名称数组长度更新它,然后在查询中使用:

db.accommodations.find({"NamesArrayLength": {$gt: 1} });

It will be better solution, and will work much faster (you can create index on it).

这将是更好的解决方案,并且运行速度会更快(您可以在其上创建索引)。

回答by JohnnyHK

There's a more efficient way to do this in MongoDB 2.2+ now that you can use numeric array indexes in query object keys.

现在您可以在查询对象键中使用数字数组索引,在 MongoDB 2.2+ 中有一种更有效的方法来执行此操作。

// Find all docs that have at least two name array elements.
db.accommodations.find({'name.1': {$exists: true}})

You can support this query with an index that uses a partial filter expression (requires 3.2+):

您可以使用使用部分过滤器表达式的索引支持此查询(需要 3.2+):

// index for at least two name array elements
db.accommodations.createIndex(
    {'name.1': 1},
    {partialFilterExpression: {'name.1': {$exists: true}}}
);

回答by Tobia

I believe this is the fastest query that answers your question, because it doesn't use an interpreted $whereclause:

我相信这是回答您问题的最快查询,因为它不使用解释$where子句:

{$nor: [
    {name: {$exists: false}},
    {name: {$size: 0}},
    {name: {$size: 1}}
]}

It means "all documents except those without a name (either non existant or empty array) or with just one name."

它的意思是“除了没有名称(不存在或空数组)或只有一个名称的文档之外的所有文档”。

Test:

测试:

> db.test.save({})
> db.test.save({name: []})
> db.test.save({name: ['George']})
> db.test.save({name: ['George', 'Raymond']})
> db.test.save({name: ['George', 'Raymond', 'Richard']})
> db.test.save({name: ['George', 'Raymond', 'Richard', 'Martin']})
> db.test.find({$nor: [{name: {$exists: false}}, {name: {$size: 0}}, {name: {$size: 1}}]})
{ "_id" : ObjectId("511907e3fb13145a3d2e225b"), "name" : [ "George", "Raymond" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225c"), "name" : [ "George", "Raymond", "Richard" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225d"), "name" : [ "George", "Raymond", "Richard", "Martin" ] }
>

回答by one_cent_thought

You can use aggregate, too:

您也可以使用聚合:

db.accommodations.aggregate(
[
     {$project: {_id:1, name:1, zipcode:1, 
                 size_of_name: {$size: "$name"}
                }
     },
     {$match: {"size_of_name": {$gt: 1}}}
])

// you add "size_of_name" to transit document and use it to filter the size of the name

// 您将“size_of_name”添加到传输文档并使用它来过滤名称的大小

回答by Aman Goel

Try to do something like this:

尝试做这样的事情:

db.getCollection('collectionName').find({'ArrayName.1': {$exists: true}})

1 is number, if you want to fetch record greater than 50 then do ArrayName.50 Thanks.

1 是数字,如果你想获取大于 50 的记录,那么做 ArrayName.50 谢谢。

回答by lesolorzanov

None of the above worked for me. This one did so I'm sharing it:

以上都不适合我。这个是这样做的,所以我要分享它:

db.collection.find( {arrayName : {$exists:true}, $where:'this.arrayName.length>1'} )

回答by Sagar Veeram

You can use $expr( 3.6 mongo version operator ) to use aggregation functions in regular query.

您可以使用$expr( 3.6 mongo version operator ) 在常规查询中使用聚合函数。

Compare query operatorsvs aggregation comparison operators.

比较query operatorsvs aggregation comparison operators

db.accommodations.find({$expr:{$gt:[{$size:"$name"}, 1]}})

回答by Yadvendar

db.accommodations.find({"name":{"$exists":true, "$ne":[], "$not":{"$size":1}}})

回答by Daniele Tassone

MongoDB 3.6 include $expr https://docs.mongodb.com/manual/reference/operator/query/expr/

MongoDB 3.6 包括 $expr https://docs.mongodb.com/manual/reference/operator/query/expr/

You can use $expr in order to evaluate an expression inside a $match, or find.

您可以使用 $expr 来计算 $match 或 find 中的表达式。

{ $match: {
           $expr: {$gt: [{$size: "$yourArrayField"}, 0]}
         }
}

or find

或找到

collection.find({$expr: {$gte: [{$size: "$yourArrayField"}, 0]}});

回答by Barrard

I found this solution, to find items with an array field greater than certain length

我找到了这个解决方案,以查找数组字段大于特定长度的项目

db.allusers.aggregate([
  {$match:{username:{$exists:true}}},
  {$project: { count: { $size:"$locations.lat" }}},
  {$match:{count:{$gt:20}}}
])

The first $match aggregate uses an argument thats true for all the documents. If blank, i would get

第一个 $match 聚合使用一个对所有文档都为真的参数。如果空白,我会得到

"errmsg" : "exception: The argument to $size must be an Array, but was of type: EOO"