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

In this particular case, everything works fine, except when for fields field1 , field2 , and field1 is 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 Result:

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

Yes, you can format the subfields on the program side and send the root field to the mongodb request, but my question is whether this is possible on the request side without Javascript.

+6
source share
4 answers

This is an unusual behavior, or rather a mistake.

From reliable / official sources:

It seems that the error is still open.

Please let me know if you need further analysis.

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

This gives the expected result.

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

This will give the result.

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

0
source

As soon as you use the projection (the second json document is in "find ()", the server will return only those fields that are specified in the forecast (the exception is "_id", which will be returned if _id: is not explicitly disabled.)

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

By selecting data.amounts.dollar inside the subdocument, you essentially disabled the other elements of the data.amounts document. You can include them in the same way as with the dollar, but I think you want all of them to be projected regardless of whether or not the field names are known.

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

From Mongo Documentation here

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

0
source

All Articles