I'm using the mongodb driver for node.js to query my MongoDB document store.
I have the following data in a document store named companies:
{
companyName: "My Company",
users: [
{
first: "Nick",
last: "Kewney",
email: [email protected],
username: "this.username",
company: "Test Company",
}
],
_id: ObjectId("54a0831fcad79dbf082d65e0")
}
I want to query the store and find any users with the username 'this.username' and return the first.
My attempt below returns the single result but as an array.
db.companies.findOne({ "users.username": "this.username" }, {_id: 0, 'users.$': 1}, next);
Returns...
{
"users": [
{
"first": "Nick",
"last": "Kewney",
"email": "[email protected]",
"username": "this.username",
"company": "Test Company"
}
]
}
My desired result is only the first item, e.g.
{
"first": "Nick",
"last": "Kewney",
"email": "[email protected]",
"username": "this.username",
"company": "Test Company"
}
users[0]from thefindOne()result. That's certainly more efficient than server-side contortions to achieve the same outcome.