I am working on querying a Nested Json in the mongo db,the sample data structure is shown below:
{
"_id" : ObjectId("5bf159cc6bf6ab0ac374f80c"),
"name" : "Jack",
"age" : "30",
"info" : {
"0" : {
"status" : "true",
"name" : "luffy"
},
"1" : {
"status" : "true",
"name" : "sanji"
},
"2" : {
"status" : "false",
"name" : "zoro"
}
}
}
/* 2 */
{
"_id" : ObjectId("5bf15f286bf6ab0ac374f8ed"),
"name" : "Mack",
"age" : "33",
"info" : {
"0" : {
"status" : "true",
"name" : "naruto"
},
"1" : {
"status" : "true",
"name" : "sakura"
},
"2" : {
"status" : "false",
"name" : "sasuke"
Now what I wanted to do is query and fetch those results where status = 'true'.After some googling I came to know how to query a nested document and came up with a sample.
query:db.getCollection('test').find({"info.0.status":"true"})
But as you know from the above query, the query will only fetch the appropriate results from the '0th' array,How do I get the query to iterate through the arrays and return documents with "status":"true" .Also I am new to Mongodb, kindly ignore any mistakes.
Note: One of the users told me I Should remodel my data structure as shown below and then use $filter operator:
[
{
"_id": ObjectId("5bf159cc6bf6ab0ac374f80c"),
"name": "Jack",
"age": "30",
"info": [
{
"status": "true",
"name": "luffy"
},
{
"status": "true",
"name": "sanji"
},
{
"status": "false",
"name": "zoro"
}
]
},
{
"_id": ObjectId("5bf15f286bf6ab0ac374f8ed"),
"name": "Mack",
"age": "33",
"info": [
{
"status": "true",
"name": "naruto"
},
{
"status": "true",
"name": "sakura"
},
{
"status": "false",
"name": "sasuke"
}
]
}
]
However I am not getting how to remodel my structure in the way that the user has shown.Is there any other tactic I could use?