Steven Luo
Steven Luo

Reputation: 2548

Complex query of MongoDB

I have looked up the manual of MongoDB, but cannot find a proper solution to do the following search:

Document structure:

{
    "_id" : ObjectId("57201082e92c07baef62452a"),
    "user_id" : 1,
    "profile" : [ 
        {
            "date" : ISODate("2012-10-11T12:58:06.000Z"),
            "content" : [ 
                {
                    "feature_id" : 1,
                    "feature_value" : true
                }
            ]
        },
        {
            "date" : ISODate("2013-04-12T8:23:09.000Z"),
            "content" : [ 
                {
                    "feature_id" : 1,
                    "feature_value" : false
                }
            ]
        }
    ]
}

What I want to get is the LATEST feature_value of a given user_id and a given feature_id.

Is there any way to accomplish this using MongoDB?

Thanks.

Upvotes: 0

Views: 91

Answers (2)

Shantanu Madane
Shantanu Madane

Reputation: 615

Please try this:

db.test.aggregate(
{$match:{"user_id" :1,"profile.content.feature_id":1}},
{$project:{"profile.content.feature_value":1}},
{$sort:{"profile.date" :-1}},
{$limit : 1});

Upvotes: 0

achuth
achuth

Reputation: 1212

Assuming the latest(as profile.date) you can use the following to get the desired result.(query not tested, hope it works).

db.test.aggregate(
[
  {$match : {"user_id" : 1}},
  {$unwind : "$profile"},
  {$unwind : "$profile.content"},
  {$match : {"profile.content.feature_id" : 1}},
  {$sort : {"profile.date" : -1}},
  {$limit : 1},
  {$group:{_id : "$_id", content : {$push:"$profile.content"}}}
 ])

Upvotes: 1

Related Questions