0

I am having some trouble trying to query a field in Mongo. My document looks like this:

{
    "short_url": "DTsB9k",
    "long_url": "http://www.example.com",
    "date_created": {
        "$date": "2013-01-01T14:10:29.899Z"
    },
    "ips": {
        "24.184.209.227": {
            "ip_address": "12.34.56.78",
            "clicks": [
                {
                    "click_date": {
                        "$date": "2013-01-01T14:10:41.784Z"
                    },
                    "click_referrer": null
                },
                {
                    "click_date": {
                        "$date": "2013-01-01T14:31:32.440Z"
                    },
                    "click_referrer": null
                }
            ]
        }
    },
    "users": {
        "4": {
            "user_id": "4",
            "date_added": {
                "$date": "2013-01-01T14:10:29.899Z"
            },
            "creator": true
        }
    },
    "total_clicks": 2,
    "_id": {
        "$oid": "50e2ee55569df0b469000000"
    }
}

I'm trying to query on the user_id, eventually there will be more than one. But I've tried

{ "users" : "4" }
{ "users.user_id" : "4" }
{ "users.*.user_id" : "4" }

None of these work. What am I doing wrong in this?

1 Answer 1

2
  1. {"users":4} would find only documents with users field which is equal to 4, or users field which is equal to an array containing an element which equals to 4

  2. {"users.user_id":4} would have worked if you had user_id directly under the users object, but it is under the "4", so it fails to match

  3. { "users.*.user_id" : "4" } I don't think mongodb has such wildcard feature.

To fetch the record above you can try:

{"users.4.user_id": "4"}


edit: If the "4" under "users" is the same as the user_id, you can also try the query:

{"users.4":{$exists:true}}

Sign up to request clarification or add additional context in comments.

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.