Reputation: 57
I created an embedded document named "KPOP" in MongoDB, and I wanted to find the field with the value of "BTS: Fake Love"
Here is the embedded document:
> use TestMongoDB
switched to db TestMongoDB
> db.KPOP.find().pretty()
{
"_id" : ObjectId("5fd83447066c904c1365771a"),
"KPOP" : {
"SHINee" : "Dream Girl",
"Girl's Generation" : "I Got a Boy",
"BTS" : "Fake Love"
}
}
Is something wrong with my code? After I press enter, nothing shows up.
> db.KPOP.find( {"KPOP": {"BTS": "Fake Love"}} )
Upvotes: 0
Views: 123
Reputation: 14287
Is something wrong with my code? After I press enter, nothing shows up.
db.KPOP.find( {"KPOP": {"BTS": "Fake Love"}} )
That is the expected behavior.
If you want to query an embedded document's individual field(s) you need to use the following syntax - using the dot (.
) notation. For example, both these queries return the document:
db.test.find({"KPOP.SHINee": "Dream Girl"})
db.test.find({"KPOP.SHINee": "Dream Girl", "KPOP.BTS": "Fake Love" })
In the above queries, you can specify one, two or all the fields and in any order.
You use the following syntax when specifying the filter for the whole embedded document:
db.test.find({ KPOP: { SHINee: "Dream Girl", "Girl's Generation": "I Got a Boy", BTS: "Fake Love" } })
In this case, note that the order of the fields of the embedded document must be same as that of the original document; i.e., SHINee
, "Girl's Generation"
and BTS
(within the KPOP
). And, you need to specify all the fields of the embedded document.
Upvotes: 2