Home > other >  How can i get distinct values from my mongodb
How can i get distinct values from my mongodb

Time:09-08

So, in my application i want to get all the values of the property "Alimento"

    {
    "foods": [
        {
            "_id": "6318c906904b22a684659009",
            "Alimento": "Papinha Infantil de Ameixa NESTLÉ",
            "CategoriaDeAlimentos": "Alimento Infantil",
            "TabelaNutricional": [
                {
                    "Calorias": 0.83,
                    "Carboidratos": 0.19,
                    "Proteína": 0,
                    "Gorduta Total:": 0.02,
                    "Sódio": 0
                }
            ]
        },
        {
            "_id": "6318c906904b22a68465900a",
            "Alimento": "Papinha Infantil de Banana NESTLÉ",
            "CategoriaDeAlimentos": "Alimento Infantil",
            "TabelaNutricional": [
                {
                    "Calorias": 0.67,
                    "Carboidratos": 0.16,
                    "Proteína": 0,
                    "Gorduta Total:": 0,
                    "Sódio": 0
                }
            ]
        },
    ]
}

I am trying to get the values using the distinct method, as i have used many times before in react with help of mongoose (now im using nextjs with mongodb), but im getting an error.

    const handler = async (req, res) => {
      const { db } = await databaseConnection();
    
      try {
        const foodCaterogies = await db.collection('foods').find({}).distinct().toArray();
    
        res.status(200).json({ foods: foodCaterogies });
      } catch (error) {
        console.log(error);
      }
    };

The error:

        db.collection(...).find(...).distinct is not a function

CodePudding user response:

You can find it by a query parameter. Hope it will help you:

app.get('/myFood', async(req, res) =>{
  const Alimento = req.query.Alimento;
  const query = {Alimento: Alimento};
  const foodAlimento = await foodCollection(YourCollectionName of DB).find(query).toArray();
  console.log(foodAlimento);
  res.send(foodAlimento);
})

CodePudding user response:

Query

  • if foods is the collection, and those 2 are sample documents of foods
  • you can group by Alimento to get the distinct values

*i am not sure what output you want, thats why i asked you to added, but this finds all the distinct values in the collection

Playmongo

foods.aggregate([{"$group": {"_id": "$Alimento"}}])
  • Related