jms
jms

Reputation: 182

ordered fixed-length arrays in mongoDB

I'm new to monogDB and trying to design the way I store my data so I can do the kinds of queries I want to. Say I have a document that looks like

{
    "foo":["foo1","foo2","foo3"],
    "bar":"baz"
}

Where the array "foo" is always of length 3, and the order of the items are meaningful. I would like to be able to make a query that searches for all documents where "foo2" == something. Essentially I want to treat "foo" like any old array and be able to index it in a search, so something like "foo"[1] == something.

Does monogDB support this? Would it be more correct to store my data like,

{
    "foo":{
        "foo1":"val1",
        "foo2":"val2",
        "foo3":"val3"
    },
    "bar":"baz"
}

instead? Thanks.

Upvotes: 4

Views: 192

Answers (1)

world
world

Reputation: 3952

The schema you have asked about is fine.

To insert at a specific index of array: Use the $position operator. Read here.

To query at a specific index location: Use the syntax key.index. As in:

db.users.find({"foo.1":"foo2"})

Upvotes: 2

Related Questions