Reputation: 161
I have the document in MongoDB like --
{
name: "Myname",
Auth: "myAuth",
Books:[{
b_name: "bookname",
b_type: "tech",
datetime: "datetime"
}],
dept: "IT"
}
Now If I just want to get the name field based upon filter condition, I can query like --
db.books.find( { dept: "IT" } , { Myname:1, Auth:1, _id:0 } )
But if I want to get one single field as well as one of the array field in the array "Books"
, how do I query the MongoDB
.
I want something like --
db.books.find( { dept: "IT" } , { Myname:1, Auth:1, Books.b_name:1, _id:0 } )
The above query will not work.
Upvotes: 0
Views: 112
Reputation: 12975
Projection attributes are JSON/doccument fields . You have no field like Myname . Secondly you have to use quotes for sub document like 'Books.b_name'
Query :
db.books.find( { dept: "IT" } , { name:1, 'Auth':1, 'Books.b_name':1, _id:0 } ) ;
Output :
{ "name" : "Myname", "Auth" : "myAuth", "Books" : [ { "b_name" : "bookname" } ] }
Upvotes: 1