O
O
olezhenka2018-05-14 10:45:22
MongoDB
olezhenka, 2018-05-14 10:45:22

How to get a specific object in an array?

I have a base Groups.
Groups has settings.

const Groups = new Schema({
  group_id: Number,
  settings: [
    {
      name: String
    }
  ]
})

Let's say we have this document:
{
  group_id: 12312,
  settings: [
    {
      name: 'world1'
    },
    {
      name: 'world2'
    },
    {
      name: 'world3'
    }
  ]
}

I want to get a group but with only one settings object I need, like this:
{
  group_id: 12312,
  settings: {
    name: 'world2'
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
3
3vi1_0n3, 2018-05-14
@olezhenka

It's not entirely clear what else is there, but perhaps unwind from the aggregate framework will do.
Something like this:

> db.groups.find();
{ "_id" : ObjectId("5af95ce4b538395ae8af74fd"), "group_id" : 12312, "settings" : [ { "name" : "world1" }, { "name" : "world2" }, { "name" : "world3" } ] }
> db.groups.aggregate({$unwind: "$settings"}, {$match: {"settings": {"name":"world2"}}});
{ "_id" : ObjectId("5af95ce4b538395ae8af74fd"), "group_id" : 12312, "settings" : { "name" : "world2" } }

Mongoose should be able to do this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question