M
M
mr jeery2018-09-06 23:42:10
MongoDB
mr jeery, 2018-09-06 23:42:10

How to find in mongodb by object key name?

5b91904dda6af868616979.png
I have a sessions object where each time a new property-object named session_id is added.
I need to find a user who has a property named session_id in the sessions object.
How to do it ?
Tried through where, it is impossible.
Is it possible to enter a string in place of session_id, but how to pass a variable, it gives an error that session_id is undefined

const {username, session_id} = user
    console.log('/load',session_id)
    let result = null;
      User.findOne({ $where: function() {
        if (this.sessions["<session_id>"]) {
          return true
        }

      } }, {username: 1, email: 1})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lega, 2018-09-07
@lega

Плохое решение, так сессию не заиндексировать - а значит монга будет делать full scan коллекции, что приведет к тормозам при росте коллекции.
Как компромис - можете продублировать сессю в массив и сделать на него индекс.

M
mr jeery, 2018-09-07
@jeerjmin Автор вопроса

Сам отвечаю на вопрос, может кому пригодится.
Есть волшебное слово exists для таких случаев.

const own_name = 'sessions.' + session_id
    const query = {}
    query[own_name] = { $exists: true }

      User.find(query)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question