Reputation: 1157
Am using mongo to store my documents. And one of them looks like below.
Name:
first: joe
last: blo
address:
city: Paris
state: London
relatives:
first order:
aunt: ashley
uncle: tom
second order
aunt: roma
uncle: robin
I would like to be able to perform a query which would give me documents that match 'aunt':'roma'. Am using mongo java api to access it
From what I have understood and read the following query should work, but it doesnt
DBObject winner = new BasicDBObject("$match", new BasicDBObject("aunt", "roma") );
System.out.println("count "+coll.aggregate(winner).getCommandResult());
Can anyone help me understand and explain why this is failing?
Thanks K
Upvotes: 0
Views: 432
Reputation: 1185
My suggestion is that, for better understanding, you practice a bit using the MongoDb javascript console to test your queries first against your database collections, then later you get to write them directly for the driver you are using (Java in your case). An example:
To match a document described like this
{
name: {
first: "joe",
last: "blo"
} ,
address: {
city: "Paris",
state: "London"
},
relatives: {
first_order: {
aunt: "ashley",
uncle: "tom"
},
second_order: {
aunt: "roma",
uncle: "robin"
}
}
}
you would build a query like this
db.my_collection.find({"relatives.second_order.aunt": "roma"})
To have the document inserted into a collection called my_collection
, it´s simple as
db.my_collection.insert(
{
name: {
first: "joe",
last: "blo"
} ,
address: {
city: "Paris",
state: "London"
},
relatives: {
first_order: {
aunt: "ashley",
uncle: "tom"
},
second_order: {
aunt: "roma",
uncle: "robin"
}
}
})
Some references you may read to get your queries properly written to Java API: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
And the docs for playing around with the MongoDb console, in this case with querying subdocuments: http://docs.mongodb.org/manual/reference/method/db.collection.find/#query-subdocuments
Hope it helps.
Upvotes: 1