Oliver
Oliver

Reputation: 928

How can i select all(selected) records in a mongo find?

Question: How can i select all(selected) records in a mongo find? It seems to only return one result in RoboMongo even though i think i chose to get back two?

In this case it is a set of "X/Y" so they need to match with $and i would believe unless i would start to merge them into one field. In a classical SQL Query i would probably write something like

select x,y from map_table where (x = 69 and y = 69) or (x = 68 and y = 69)

I believe this would return both rows. Maybe i'm making things too complicated or I've got a mistake in my model and this is not applicable to mongodb.

Background: I'm writing an application with coordinates "X/Y" a classical tile in my DB consists of a object containing these two variables inside. I've got a compound index on it in the same order "X/Y". In the middle of development I've realized that only one record is returned and started to put the query into RoboMongo and check it. The final idea is to select between 20-100 tiles in one go.

db.map.find({"$or" : [{ 
                  "$and" : [ 
                {
                    "X" : 69
                }, 
                {
                    "Y" : 69
                }
            ],
                "$and" : [ 
                {
                    "X" : 68
                }, 
                {
                    "Y" : 69
                }]
            }]  

    })

The result of that query is really:

{ "_id" : ObjectId("580aabcd7ad9aa2b404af79f"), "X" : 68, "Y" : 69, "ID" : 4830 }

What i would expect?

{ "_id" : ObjectId("580aabcd7ad9aa2b404af79f"), "X" : 68, "Y" : 69, "ID" : 4830 }

{ "_id" : ObjectId("580aabcd7ad9aa2b404af89f"), "X" : 69, "Y" : 69, "ID" : 4830 }

If the second $and clause is changed to 69,69 it will show up that specific record, i don't know why this is happening maybe i'm missing some crucial information on how to "find" records in mongodb.

Upvotes: 0

Views: 412

Answers (1)

s7vr
s7vr

Reputation: 75964

If you look carefully, the brackets positioning is incorrect.

Incorrect - 12

db.map.find({
    $or: [{
        $and: [{}, {}],
        $and: [{}, {}]
    }]
})

Correct - 14

db.map.find({
    $or: [{
        $and: [{}, {}]
    }, {
        $and: [{}, {}]
    }]
})

So change your query to

db.map.find({
    "$or": [{
        "$and": [{
            "X": 69
        }, {
            "Y": 69
        }]
    }, {
        "$and": [{
            "X": 68
        }, {
            "Y": 69
        }]
    }]
})

Upvotes: 1

Related Questions