DhruvPathak
DhruvPathak

Reputation: 43265

How to get all subfields of mongodb in a query when one field is root field of other field requested?

For this specific case, everything works fine, except when for the fields field1,field2 requested, and field1 is a part of field2.

Example :

> db.mycoll.findOne()
{
    "_id" : 1,
    "data" : {
        "amounts" : {
            "dollar" : 20,
            "euro" : 18
        },
        "item" : "toy",
        "sale" : false
    }
}

   // works well
> db.mycoll.findOne({"_id":1},{ "data.amounts.dollar":1 })
{ "_id" : 1, "data" : { "amounts" : { "dollar" : 20 } } }



   // here "data" is root of "data.amounts.dollar" and "data.amounts.euro" 
   //   takes preference, how to query for "data", so 
   //   that all subfields of data are 
   //     returned
> db.mycoll.findOne({"_id":1},{ "data":1 , "data.amounts.dollar":1 })
{ "_id" : 1, "data" : { "amounts" : { "dollar" : 20 } } }

Expected output :

 {
        "_id" : 1,
        "data" : {
            "amounts" : {
                "dollar" : 20,
                "euro" : 18
            },
            "item" : "toy",
            "sale" : false
        }
    }

Yes, it is possible to format the subfields on the program side, and send the root field to mongodb query, but my question is if this is feasible on the querying side without Javascript .

Upvotes: 6

Views: 2003

Answers (4)

inaitgaJ
inaitgaJ

Reputation: 1487

This is unusual behavior, a bug to be precise.

From credible/official sources :

Seems that the bug is still open.

Please let me know if you need any further analysis.

Upvotes: 6

jimper
jimper

Reputation: 51

Once you use a projection (the second json document in the 'find()', only those fields specified in the projection will be returned by the server (The exception is '_id' which will be returned unless explicitly turned off by _id:0).

{ "data":1 , "data.amounts.dollar":1 }

By selecting data.amounts.dollar inside the sub-document, you have essentially turned off the other members of the data.amounts document. You can turn them on like you did with dollar, but I think you want them all projected regardless of knowing or not the field names.

I could not find in the documentation anything about order of fields in the projection field.

From the Mongo Documentation here

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#projection-document

Upvotes: 0

Vaibhav Patil
Vaibhav Patil

Reputation: 3023

This gives as expected result

db.getCollection(coll_name).find({_id:1},{data:1});

This will give output

{ "_id" : 1, "data" : { "amounts" : { "dollar" : 20, "euro" : 18 }, "item" : "toy", "sale" : false } }

Upvotes: 0

RootHacker
RootHacker

Reputation: 1107

db.mycoll.findOne({"_id":1},{"data.amounts.dollar":1,"data":1 })

Upvotes: 1

Related Questions