我有一个MongoDB集合的文档格式如下:

{
  "_id" : ObjectId("4e8ae86d08101908e1000001"),
  "name" : ["Name"],
  "zipcode" : ["2223"]
}
{
  "_id" : ObjectId("4e8ae86d08101908e1000002"),
  "name" : ["Another ", "Name"],
  "zipcode" : ["2224"]
}

我目前可以获得匹配特定数组大小的文档:

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

这将正确地返回name数组中有2个元素的文档。但是,我不能用$gt命令返回name字段数组大小大于2的所有文档:

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

如何选择名称数组大小大于1的所有文档(最好不必修改当前数据结构)?


当前回答

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

其他回答

虽然上面的答案都工作,你最初尝试做的是正确的方式,然而你只是有语法向后(切换“$size”和“$gt”)..

正确的:

db.collection.find({items: {$gt: {$size: 1}}})

以上这些方法对我都没用。这一个做到了,所以我分享一下:

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

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

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

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

或者找

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

你也可以使用aggregate:

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

//你添加"size_of_name"到传输文档,并使用它来过滤名称的大小

在MongoDB 2.2+中,现在可以在查询对象键中使用数值数组索引(基于0),这是一种更有效的方法。

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

你可以通过使用偏过滤器表达式的索引来支持这个查询(需要3.2+):

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