Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

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 .

like image 789
DhruvPathak Avatar asked Sep 13 '16 12:09

DhruvPathak


People also ask

How do I select a single field for all documents in a MongoDB collection?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I query a nested field in MongoDB?

In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks. Document: three documents that contain the details of the students in the form of field-value pairs.

Which method will you use to find multiple data from the MongoDB server?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.

How get all items from MongoDB?

Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.


2 Answers

This is unusual behavior, a bug to be precise.

From credible/official sources :

  • Jira Open Bug
  • Jira Bug Duplicate

Seems that the bug is still open.

Please let me know if you need any further analysis.

like image 138
inaitgaJ Avatar answered Sep 28 '22 07:09

inaitgaJ


db.mycoll.findOne({"_id":1},{"data.amounts.dollar":1,"data":1 })
like image 26
RootHacker Avatar answered Sep 28 '22 07:09

RootHacker