问题描述:

I have something like this for every user in mongoDB:

{

"id" : 1234,

"name" : "Mr. Someone",

"userdata" : {

"living" : {

"city" : "Somecity",

"address" : "Main Street 10.",

"zip" : "1023"

},

"interest" : "Cars"

}

I'm trying to find a way to count how many subscribers live in Somecity.

My best guess was the following:

db.users.count({userdata:{living:{city:"Somecity"}}}

But the result was 0.

How can I properly count "rows" by a given value in mongoDB?

I'm using mongoDB's documentation (for example: http://docs.mongodb.org/manual/reference/sql-comparison/) but could not resolve my problem yet.

I'm using mongoDB trough shell.

网友答案:

I think I have found the sollution to my problem:

db.users.count({"userdata.living.city":"Somecity"})

This "dotting" method allowed me to search for only one value in the array, while the method I tried first wanted to find an exact match.

Further reading: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/

Quote:

Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query:

db.survey.find( { "results.product": "xyz" } )

相关阅读:
Top