I am new to Mongo so any help is appreciated.
I have a User object and in it multiple more objects which are hosting client data based on the User's interaction with each one.
This is how it looks like
db.users.findOne(
{"clients.clientId":35},
{"clients.clientId":1}
)
{
"_id" : ObjectId("586670e6ce9287cf6d197d14"),
"clients" : [
{ "clientId" : 35 },
{ "clientId" : 67 },
{ "clientId" : 73 },
{ "clientId" : 78 },
{ "clientId" : 82 }
]
}
As you can see from my query, it returns a User that has data from client 35 but also returns data from every other client.
How can I access only the data from client 35?
You have an embedded array of documents on the clients key.
Your query projection {"clients.clientId":1} states that the query should return only that key, clients key. Your clients field is an array, therefore all embedded documents from the array will be extracted (projected).
When you want only one element in the array to be displayed, the one defined in the query i.e. the client with id 35 {"clients.clientId":35}, need to use the projection positional operator $:
db.users.findOne({"clients.clientId":35},{"clients.$":1})
Result:
{
"_id" : ObjectId("586670e6ce9287cf6d197d14"),
"clients" : [
{
"clientId" : 35
}
]
}
Note: using $ operator, it will project only the first element in the array that matches the query; if you have more documents in the array having the same value, only the first will be displayed.