码迷,mamicode.com
首页 > 其他好文 > 详细

mongo中查询Array类型的字段中元素个数

时间:2015-11-12 11:45:55      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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 }})

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

db.accommodations.find({ name : { $size: { $gt : 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)?

 

解决办法:

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

2.db.accommodations.find({‘name.1‘: {$exists: true}})

说明:name.1是name字段(Array类型)的第二个索引(从0开始)

mongo中查询Array类型的字段中元素个数

标签:

原文地址:http://www.cnblogs.com/ericgisser/p/4958208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!