0

Say I have a Foo document like the following:

{
  _id: 1,
  bar: [{_id: 1, ...bar props}, {_id: 2, ...bar props}, {_id: 3, ...bar props)}],
  ... other foo props
}

How do I query the database for a single Bar, such that my result looks like:

{_id: 2, ...bar props}

Something like:

db().collection('foo').findOne({ _id: 1, {foo: _id: 2}}, {foo: 1, _id: 0})

old greg
  • 799
  • 8
  • 19
  • Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – turivishal Apr 23 '21 at 15:19
  • No, the example in the linked question shows the result is an array of Foo, I want to retrieve a single Foo. – old greg Apr 23 '21 at 15:20
  • All the possibly answers are covered in that question, for `find()` possible solution is this [answer](https://stackoverflow.com/a/41010776/8987128) and for `aggregate()` best solution is this [answer](https://stackoverflow.com/a/12241733/8987128) – turivishal Apr 23 '21 at 15:25

1 Answers1

2

Matching and projection are separate operations in MongoDB and you should also keep them separate when you are thinking (and asking) about queries.

You cannot "query for a single Bar". Queries always match documents. What you can do is find a document which contains a Bar which matches conditions, or you can find a document which contains exactly one Bar which also matches conditions, etc. In all of these cases you still get the top-level document(s) as a result.

To retrieve (only) one, several or all of the Bars in whichever documents matched your query conditions, instead of those documents, use projection (either second argument to find or $project aggregation pipeline stage).

When you are using the aggregation pipeline, you can mix $match and $project stages so that, for example, you $match to filter down documents, then $project to reduce the documents to some of their fields, then $match to further filter down the resulting documents, and so on. Still matching and projection are separate operations.

D. SM
  • 13,584
  • 3
  • 12
  • 21