0

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.

1
  • Do you mean the last element in the "profile" array? Commented Apr 27, 2016 at 7:13

2 Answers 2

1

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"}}}
 ])
Sign up to request clarification or add additional context in comments.

Comments

0

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});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.