Z
Z
zbender2014-01-30 14:12:34
MongoDB
zbender, 2014-01-30 14:12:34

What query in mongodb can get objects containing an object with a field equal to "x"?

For example, we have the following objects in the collection:

"id" : 1,
"visits" : [ 
        {
            "userId" : "1",
            "date" : 1390482788
        }, 
        {
            "userId" : "2",
            "date" : 1386912055
        },

What query can get all objects that have the field visits[x]['userId'] = 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nekipelov, 2014-01-30
@zbender

db.collection.find( {visits: {userId: 1}} );
or
db.collection.find( {"visits.userId": 1} );

A
Andrew, 2014-01-30
@kaasius

Maybe it is possible somehow through dot-notation and $elemMatch, but this is some kind of wrong architecture. Indexes won't work that way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question