0

I have an object below.

{
    "_id" : "8LEfPt57rWHZ8ebdS",
    "createdAt" : ISODate("2015-04-07T16:00:30.798Z"),
    "services" : {
        "password" : {
            "bcrypt" : "$2a$10$SIUgFIWTq6nBmTIqNjMYFOSKtds.yR26fm8yblbcRm3yYeg.rH3jK"
        },
        "resume" : {
            "loginTokens" : [
                {
                    "when" : ISODate("2015-04-07T16:00:30.992Z"),
                    "hashedToken" : "Qnq4m/ETqI/heHPIYGdAJIyYQJNQ0EH5MFgDjgQt2GY="
                },
                {
                    "when" : ISODate("2015-04-09T14:49:08.652Z"),
                    "hashedToken" : "xxm3xXggjT1v8vcaY4/uLXUtPdMKyXaPp7xCLF6gBeM="
                }
            ]
        }
    },
}

I want to get the list of users,who has logged in a date range .

But I am not getting any result for below query.

db.users.find({ 'services.resume.loginTokens': { $elemMatch: { when:  { '$lte': '2015-04-11T18:29:59.999Z', '$gte': '2015-04-04T18:29:59.999Z' } } } })

Can anyone will help me on this.

2 Answers 2

1

Mongo aggregation pipline and mongo aggregation $and operator will find your exact result. Check below query

db.collectionName.aggregate({
    "$unwind": "$services.resume.loginTokens"
}, {
    "$match": {
    "$and": [{
        "services.resume.loginTokens.when": {
            "$lt": ISODate("2015-04-11T18:29:59.999Z")
        }
    }, {
        "services.resume.loginTokens.when": {
            "$gt": ISODate("2015-04-04T18:29:59.999Z")
        }
    }]
    }
}).pretty()
Sign up to request clarification or add additional context in comments.

Comments

0

Its quite simple.. You have to put ISODate format date to check in query, because you are having date in ISO format in DB and its not a string , you can write this type of query for strings, so

Replace your query

db.users.find({ 'services.resume.loginTokens': { $elemMatch: { when: { '$lte': '2015-04-11T18:29:59.999Z', '$gte': '2015-04-04T18:29:59.999Z' } } } })

to this

db.dummy.find({ 'services.resume.loginTokens': 
{ $elemMatch: { when: { $lte: ISODate('2015-04-11T18:29:59.999Z'), $gte: ISODate('2015-04-04T18:29:59.999Z') } } } }) 
// added ISOdate()

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.