Search code examples
arraysmongodbfieldprojection

Projecting specified fields within an array in MongoDB (missing ] error?)


In MongoDB, I understand that to project only specified fields in a collection, I would execute:

db.collection.find({}, {"field1": 1, "field2": 1})

But what would I do if I wanted to only project specified fields within an array in a collection? The only way I can think would be this:

db.collection.find({field1: [arrayfield1: 1, arrayfield2: 1, arrayfield3: 1]})

But I get "SyntaxError: missing ] after element list (shell):1". I've tried this as well:

db.collection.find({field1: [arrayfield1: 1], [arrayfield2: 1], [arrayfield3: 1]})

And get the same error. Can anyone tell me what I'm doing wrong? Because I can't figure it out. Or if I'm on the completely wrong track?

(I'm aware that the error says "element list," and I believe it should be a field list or something to that extent, so I suspect this is not the correct way to go about what I'm trying to do.)


Solution

  • I figured it out. The answer was dot notation. This did the trick:

    db.colletion.find({}, {  "array.arrayfield1" : 1, "array.arrayfield2" : 1, "array.arrayfield3" : 1 })