按数组值查询 - MongoDB

时间:2017-12-13 15:26:54

标签: mongodb

我的收藏中有一个带有数组字段的文档:

location {
[0] = 1.99999
[1] = 3.6544321
}

如何按数组字段的值进行过滤?

如何在查找查询中仅显示位置[0]?

Thansk提前

1 个答案:

答案 0 :(得分:1)

  

如何在查找查询中仅显示位置[0]?

使用$slice仅显示阵列上所需的元素

集合中的示例文档

{ "_id" : ObjectId("5a3231d1bf7e914583df4fbf"), "location" : [ 1.99999, 3.6544321 ] }
{ "_id" : ObjectId("5a3231e1bf7e914583df4fc0"), "location" : [ 23.99999, 43.6343341 ] }
{ "_id" : ObjectId("5a3231f5bf7e914583df4fc1"), "location" : [ 12.2323, 11.2879731 ] }

Mongo Shell查询

db.collection_name.find({},{"location":{$slice:[0,1]}});

结果

{ "_id" : ObjectId("5a3231d1bf7e914583df4fbf"), "location" : [ 1.99999 ] }
{ "_id" : ObjectId("5a3231e1bf7e914583df4fc0"), "location" : [ 23.99999 ] }
{ "_id" : ObjectId("5a3231f5bf7e914583df4fc1"), "location" : [ 12.2323 ] } 
  

如何按数组字段的值进行过滤?

使用$elemMatch按值

过滤数组元素

Mongo Shell查询

db.collection_name.find({location:{$elemMatch:{$gte:12}}})

结果

{ "_id" : ObjectId("5a3231e1bf7e914583df4fc0"), "location" : [ 23.99999, 43.6343341 ] }
{ "_id" : ObjectId("5a3231f5bf7e914583df4fc1"), "location" : [ 12.2323, 11.2879731 ] }