Home > Blockchain >  How to get an object inside another object?
How to get an object inside another object?

Time:09-17

This is my collection like,

[
   {
      "column1":"data1",
      "column2":"data2",
      "column3":[
         {
            "column31":"data31",
            "column32":"data32"
         }
      ],
      "column4":"data4"
   },
   {
      "column1":"data11",
      "column2":"data22",
      "column3":[
         {
            "column31":"data312",
            "column32":"data322"
         }
      ],
      "column4":"data44"
   }
]

I want to get columns which has 'column1 : "data11"' and 'column31 : "data312"'

This is my query, but it returns null object

    collection.find({
        column1: "data11",
        column3: {
            column31 : "data312"
        }
    }).then((item)=>{
        res.json(item);
    }).catch((err)=>{
        console.log(err);
    });

How can I fix this issue?

CodePudding user response:

Change your query like this:

collection.find({
    column1: "data11",
    "column3.column31": "data312"
}).then((item)=>{
    res.json(item);
}).catch((err)=>{
    console.log(err);
});

CodePudding user response:

You have to use dot notation, otherwise you are telling mongo that matches the entire object.

So this query works:

db.collection.find({
  "column1": "data11",
  "column3.column31": "data312"
})

Example here

  • Related