2

My schema looks like

name:
value:
p_vars: {
    name1: {},
    name2: {},
}

I want to count how many items are there in p_vars.

Thinking that interpretor is JavaScript, I tried

db.collection.findOne().p_vars.length

But nothing returns

Answer should be

Considering above, answer should be 2(two items name1 and name2)

daydreamer
  • 87,243
  • 191
  • 450
  • 722

1 Answers1

3

The simplest solution here is to change your schema to use an array of p_vars, which it sounds like you want anyway. If instead the schema was:

name:
value:
p_vars: [
    name1: {},
    name2: {},
]

Then the db.collection.findOne().p_vars.length command would return 2 as you expect.

With the original schema, the only option I think you have is to write a JS function to iterate and count the elements manually.

Adam Comerford
  • 21,336
  • 4
  • 65
  • 85