Home > database >  How do I format the output of a nested mongodb query result
How do I format the output of a nested mongodb query result

Time:01-29

I would like to format the output of my MongoDB query.

The following query

db.getCollection("books").find({})

returns the following json:

{
 title: "book 1",
 numberOfReaders: 3,
 characters: [{
  name: "annie",
  age: 3,
  height: 60,
  items: {
   itemName: "watch",
   itemDesc: "tells time"
  },{
  name: "bob",
  age: 5,
  height: 100,
  items: {
   itemName: "sword",
   itemDesc: "a long metallic sword"
 }]
}

I realised that i can control the formatting for the JSON output using $ so the following query:

db.getCollection("books").find({},{
 title: "$title",
 numberOfReaders: "$numberOfReaders",
}) 

which returns the following json:

{
 title: "book 1",
 numberOfReaders: 3, // excludes the characters array
}

But how do I control the output of the json for nest arrays such that the output is as follows:

{
 title: "book 1",
 numberOfReaders: 3,
 characters: [{ // removed age, height and itemDesc for all character objects
  name: "annie", 
  items: {
   itemName: "watch",
  },{
  name: "bob",
  items: {
   itemName: "sword",
 }]
}

Furthermore, how do I do this if the characters array was wrapped around another array

{
 title: "book 1",
 numberOfReaders: 3,
 characters: [[{ // removed age, height and itemDesc for all character objects, characters property are wrapped in two arrays
  name: "annie", 
  items: {
   itemName: "watch",
  },{
  name: "bob",
  items: {
   itemName: "sword",
  }]]
}

CodePudding user response:

One option that will work for single or double array, is:

db.getCollection("books").find({},
{
  title: 1,
  numberOfReaders: 1,
  "characters.name": 1,
  "characters.items.itemName": 1
})

See how it works on the playground example - single array

See how it works on the playground example - double array

  • Related