i have a collection that is storing data in this format :
{
_id: ObjectId("51b9be6dbbdeef1e5f008cca"),
name: 'sfdsfsdfsdfsdfsd'
details: {
varA: {
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
},
varB: {
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
}
}
}
I would like to be able to expose only the varA data in this format (without the nested depth...) :
{
_id: ObjectId("51b9be6dbbdeef1e5f008cca"),
name: 'sfdsfsdfsdfsdfsd',
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
}
Unfortunately, my query (wher i'm using projection) :
db.coll.find({}, {'details.varB': 0})
return something like this :
{
_id: ObjectId("51b9be6dbbdeef1e5f008cca"),
name: 'sfdsfsdfsdfsdfsd',
details: {
varA: {
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
}
}
How can I improve the find query to return the expected format ?
Thanks a lot in advance for those who will help me ;-)
P.S. here i'm using the mongo shell to retrieve the data but i need to get this query working with node.js with node-mongodb-native.
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
Syntax: db. collection_name. find(query, projection)
find() returns the cursor of Result Set of a query by which you can iterate over the result set or print all documents.
I have done this with aggregate function only, as explained in my blog post here
For your case, this works
db.temp.aggregate (
{
$project :
{
name:"$name",
created:"$details.varA.created",
validity:"$details.varA.validity",
modified:"$details.varA.modified"
}
}
);
or
db.temp.aggregate ({$project:{name:"$name",created:"$details.varA.created",validity:"$details.varA.validity",modified:"$details.varA.modified"}});
This is the sample run
> db.temp.insert ({name:'sfdsfsdfsdfsdfsd', details: { varA : { created: "2013-06-13T12:43:25.853Z", validity: "2013-07-13T12:43:25.853Z", modified: "2013-06-13T12:43:25.853Z"}, varB : { created: "2013-06-13T12:43:25.853Z", validity: "2013-07-13T12:43:25.853Z", modified: "2013-06-13T12:43:25.853Z" } } })
> db.temp.aggregate ({$project:{name:"$name",created:"$details.varA.created",validity:"$details.varA.validity",modified:"$details.varA.modified"}});
{
"result" : [
{
"_id" : ObjectId("51b9d7151723a9c4d6bc9936"),
"name" : "sfdsfsdfsdfsdfsd",
"created" : "2013-06-13T12:43:25.853Z",
"validity" : "2013-07-13T12:43:25.853Z",
"modified" : "2013-06-13T12:43:25.853Z"
}
],
"ok" : 1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With