Quick Tip: Return Only 1 Field

in Querying, Quick Tip

Say you have a log of hits to your podcast, something like …

{ "_id" : ObjectId("4c6c753800ae261d80000009"),
  "podcastID" : 1,
  "remoteUserIP" : "10.40.52.55",
  "remoteUserSession" : "gpn1vz1crveoqtgtlbh1tgd1",
  "remoteUserAgent" : "iTunes/9.2.1 (Macintosh; Intel Mac OS X 10.6.4)
        AppleWebKit/533.17.8",
  "created" : { "date" : "8/18/2010", "time" : "5:05:12 PM" }
}

To get a quick snapshot of hits you want to bring back the last 5 IPs that have “hit” your podcast, and you only want to return the IPs not the rest of the data you store (which might be much more then in the example Document.)

Get Only the IP

To bring back only the IP you need to pass …

{"remoteUserIP" : 1}

This is much like doing the following in SQL …

SELECT remoteUserIP FROM ...

This tells find() to only bring back this one field, remoteUserIP … (1 = true)  … then we limit to 5 and sort by date/time …

Limit Fields in find()

> db.podcastlog.find({ "remoteUserIP" : 1 }).limit(5).sort(
                     {"created.date" : -1, "created.time" : -1 });

This, however will not bring back the desired result!

That’s because find() is trying to look for …

remoteUserIP = 1

Let’s Try That Again …

Easy fix however, just pass {} as you search (everything will match that) and now you can use your { “remoteUserIP” : 1 } without any problem.

You could also query {}, { “created” : 1 } to get the dates of the last 5 hits.

> db.podcastlog.find({}, { "remoteUserIP" : 1 }).limit(5).sort(
                     {"created.date" : -1, "created.time" : -1 });

Now you’ll get back just your one field, and _id of course (you will always get back _id!)

Update: As Justin Dearing points out in the comments, while _id comes back by default you can remove it as well by preforming a query like so …

db.podcastlog.find({}, { "_id": 0, "remoteUserIP" : 1 })
2 Comments
  • http://twitter.com/zippy1981 Justin Dearing

    If you don’t want to get back _id you can do the following:

    db.podcastlog.find({}, { “_id”: 0, “remoteUserIP” : 1 })

    • http://learnmongo.com/ Learn Mongo

      Thanks Justin, updated the post to include your tip!