MongoDB Querying for object property in list
Asked Answered
R

2

9

Let's say I do have a document like this:

{
    _id: "cow",
    comments: [
        {user: "karl", comment: "I like cows.", at: /*a date*/},
        {user: "harry", comment: "Cows are the best.", at: /*a date*/}
    ]
}

Now I want to collect all the comments that "karl" left in my db. Or just the ones on a certain date. The "comments" are indexed, how can I query for that?

Roundup answered 17/12, 2011 at 15:28 Comment(0)
A
12

Something like:

db.foo.find({"comments.user":"karl", "comments.at":{$gt:{dateObject}});

Haven't tested but you get the idea; you can drill down on items as such.

I'd recommend going through this site as it drives you through a great deal of interactive tutorials: Interactive Tutorial

Aerospace answered 17/12, 2011 at 15:32 Comment(0)
C
7

You should use $elemMatch to match more than one conditions in same doc.

Something like:

db.foo.find({comments: {"$elemMatch": {user: "karl", at: {$gt:{dateObject}}}})

See here for more details.

Chavey answered 17/12, 2011 at 15:42 Comment(1)
the mongodb website changed their documentation urls - anyway I updated my answer with something relevant on the new site.Chavey

© 2022 - 2024 — McMap. All rights reserved.