Arpan
Arpan

Reputation: 161

How to limit the result of a query having array in it for MongoDB document

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

Answers (1)

Sumeet Kumar Yadav
Sumeet Kumar Yadav

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

Related Questions