简体   繁体   中英

queries in mongodb command line

I want to do a query that List the cities in a specific state with populations between 6000 and 8000. in a big data. look like this :

{ "_id" : "01564", "city" : "STERLING", "loc" : [ -71.775192, 42.435351 ], "pop" : 6481, "state" : "MA" }
{ "_id" : "01566", "city" : "STURBRIDGE", "loc" : [ -72.084233, 42.112619 ], "pop" : 7001, "state" : "MA" }
{ "_id" : "01568", "city" : "WEST UPTON", "loc" : [ -71.608014, 42.173275 ], "pop" : 4682, "state" : "MA" }
{ "_id" : "01569", "city" : "UXBRIDGE", "loc" : [ -71.632869, 42.074426 ], "pop" : 10364, "state" : "MA" }

I want to return the cities in Massachusetts let say as the above example. How can I do that ? T tried to do this :

 >db.zipcodes.aggregate( [    { $group: { _id: "$city",stateName:"$state", totalPop: { $sum: "$pop" } } },
{ $match: { totalPop: { $gte: 1000  , $lte : 2000 },stateName:"Massachusetts" } } ] );

And I got this error below:

 aggregate failed
at Error (<anonymous>)
at doassert (src/mongo/shell/assert.js:11:14)
at Function.assert.commandWorked (src/mongo/shell/assert.js:254:5)
at DBCollection.aggregate (src/mongo/shell/collection.js:1278:12)
at (shell):1:13 at src/mongo/shell/assert.js:13

You do not need to use aggregation framework.

db.zipcodes.find({
   state: 'MA',
   pop: {
     $gte: 6000,
     $lte: 8000
   }
}, {city: 1})

If you need just the name of the cities (unique) you can use distinct

db.zipcodes.distinct('city', {
   state: 'MA',
   pop: {
     $gte: 6000,
     $lte: 8000
   }
})

or even use foreach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM