0

Suppose I have the following data in Mongo:

{
    "id": "foo1",
    "description": "myFoo1",
    "bars": [
        {
            "id": "foo1bar1",
            "description": "myFoo1Bar1",
            "builton": "2010-03-01T05:00:00.000Z"
        },
        {
            "id": "foo1bar2",
            "description": "myFoo1Bar2",
            "builton": "2011-03-01T05:00:00.000Z"
        }
    ]
}
{
    "id": "foo2",
    "description": "myFoo2",
    "bars": [
        {
            "id": "foo2bar1",
            "description": "myFoo2Bar1",
            "builton": "2012-03-01T05:00:00.000Z"
        },
        {
            "id": "foo2bar2",
            "description": "myFoo2Bar2",
            "builton": "2013-03-01T05:00:00.000Z"
        }
    ]
}

My question is two-fold, I suppose:

Is it possible to execute a query that will only return documents that have a bar with a date between a specified range and only return the bars that fall in that date range? So for example, if my date range was 2010-02-01 through 2010-04-01 this is what I'd want to get back:

{
    "id": "foo1",
    "description": "myFoo1",
    "bars": [
        {
            "id": "foo1bar1",
            "description": "myFoo1Bar1",
            "builton": "2010-03-01T05:00:00.000Z"
        }
    ]
}

Is this the best way to structure the data or should I do it more relationally (i.e. have two separate documents (foos and bars) and then just have a fooId field on bar)?

1 Answer 1

1

In general, you will always get a full document back. If you really want only one element of a sub array, then your best bet would be to split each "bar" into it's own document. In this case, it would probably be better to use two collections like you'd do in an RDBMs but it is also possible to just store things like this:

{
    "foo" : {
        "id": "foo1",
        "description": "myFoo1",
    }
    "id": "foo1bar1",
    "description": "myFoo1Bar1",
    "builton": "2010-03-01T05:00:00.000Z"
},
{
    "foo" : {
        "id": "foo1",
        "description": "myFoo1",
    }
    "id": "foo1bar2",
    "description": "myFoo1Bar2",
    "builton": "2011-03-01T05:00:00.000Z"
}

Ie, store the "foo" information with each bar.

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.