Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb querying for multiple parameters

I've this collections

{
    "name" : "montalto",
    "users" : [
        {
            "username" : "ciccio",
            "email" : "aaaaaaaa",
            "password" : "aaaaaaaa",
            "money" : 0
        }
    ],
    "numers" : "8",
    "_id" : ObjectId("5040d3fded299bf03a000002")
}

If I want to search for a collection with the name of montalto and a user named ciccio I'm using the following query:

db.coll.find({name:'montalto', users:{username:'ciccio'}}).count()

But it does not work. Where I went wrong?

like image 391
gaggina Avatar asked Sep 14 '25 05:09

gaggina


2 Answers

You have to use dot notation to match inside of embedded array objects:

db.coll.find({name: 'montalto', 'users.username': 'ciccio'}).count()
like image 127
JohnnyHK Avatar answered Sep 16 '25 20:09

JohnnyHK


To clarify a collection is a group of documents. So your terminology in this question is slightly off.

To access embedded documents or objects you simply use dot notation as you would in traditional javascript.

db.coll.find({name: 'montalto', 'users.username': 'ciccio'})

You can of course add the .count()on the end of that.

like image 29
Randall Hunt Avatar answered Sep 16 '25 18:09

Randall Hunt