Skip to content
arghgr edited this page Dec 22, 2014 · 28 revisions

Using MongoDB

Once you're in the mongo shell:

  • use acab_db switches to the SFPD database
  • db.incidents.find() (with nothing in the .find() parentheses) returns all incidents
  • db.incidents.find().pretty() returns all incidents in a more readable, indented format

Basic commands

Basic queries

Limit display of fields

Aggregation

Example queries

  • db.incidents.find().count()

searches incidents database and returns number of incidents matching query

  • db.incidents.find({"ZIP":"94110", "Date": { $gt:new ISODate("2014-03-04T03:00:00Z")}}, {"Category": 1, "ZIP": 1, "Date": 1, "Resolution": 1, "IncidntNum": 1, "_id": 0 }).pretty()

searches the incidents database for incidents with zip code 94110 and date greater than ($gt) March 4, 2014 at 3am, and returns only the Category, Zip code, Date, Resolution, and IncidntNum fields (and doesn't return the _id field), and displays the results in a more readable format (.pretty())

  • db.incidents.distinct("field", {query}).sort(1)

searches incidents database and returns unique values for "field" matching {query}, sorted in ascending order (descending is -1)

Aggregation

You should aggregate by "IncidntNum" because one incident may be filed under multiple categories, so there may be several incident objects that share the same IncidntNum.

  • db.incidents.aggregate([{ $group: { _id: { IncidntNum: "$IncidntNum"}, number: { "$sum": 1 } } }, { $sort: { "Date": 1 } }, { $match: { number: { $gte: 24 } } }], { allowDiskUse: true })

searches incidents database and returns incidents grouped by incident number, displays the number of objects with the same incident number, sorts by date ascending, filters for incidents that have 24 or more associated objects, and allows writing to memory.

  • db.incidents.aggregate([{ $match: { "Descript": "SUSPICIOUS PERSON" } }, { $group: { _id: { PdDistrict: "$PdDistrict"}, number: { "$sum": 1 } } }, { $sort: { number: 1 } }], { allowDiskUse: true })

searches incidents database for incidents that match the description "Suspicious Person", groups them by pd district, displays the number of objects with the same pd district, sorts by number of objects ascending, and allows writing to memory.

Clone this wiki locally