0

In my collection I have an array of objects. I'd like to share only a subset of those objects, but I can't find out how to do this?

Here are a few things I tried:

db.collections.find({},
  { fields: {
    'myField': 1, // works
    'myArray': 1, // works
    'myArray.$': 1, // doesn't work
    'myArray.$.myNestedField': 1, // doesn't work
    'myArray.0.myNestedField': 1, // doesn't work
  }
};
2
  • Did you try 'myArray.myNestedField':1 ? Commented Jan 11, 2017 at 20:18
  • That's absolutely correct! Didn't make sense to me to do that. Commented Jan 12, 2017 at 1:01

1 Answer 1

2
myArray.myNestedField':1 for projecting nested fields from the array.

I'll briefly explain all the variants you have.

'myField': 1 -- Projecting a field value
'myArray': 1 -- Projecting a array as a whole - (Can be scalar, embedded and sub document)

The below variants works only with positional operator($) in the query preceding the projections and projects only the first element matching the query.

'myArray.$': 1
'myArray.$.myNestedField': 1

This is not a valid projection operation.

'myArray.0.myNestedField': 1

More here on how to query & project documents

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.