0

I want to return all documents in a collection. But I only want a subdocument to appear in votes array if the userId matches. If it doesn't match I still want the parent document to be returned but without anything appearing in the votes array.

Actual document:

[{  "_id": "...",
    "user": {...},
    "title": "test",
    "votes": [
      {"user": "56c265fda0a4335c01205551", "vote": 1},
      {"user": "56c265fda0a4335c01205552", "vote": 1},
      {"user": "56c265fda0a4335c01205553", "vote": 1},
      {"user": "56c265fda0a4335c01205554", "vote": 1}
]}]

What I want if the filter is ...5551: (It IS in the array)

[{  "_id": "...",
    "user": {...},
    "title": "test",
    "votes": [
      {"user": "56c265fda0a4335c01205551", "vote": 1}
]}]

What I want if the filter is ...0000: (It isn't in the array)

[{  "_id": "...",
    "user": {...},
    "title": "test",
    "votes": [] //Empty array, but document is still returned.
}]

I found a lot of resources to only include documents if the search value appears in the array, and I can get that value to be the only one that appears, but all of these don't return documents if that value isn't found in the array at all.

How do I get all parent documents to be returned and then filter the votes array so only a single matching element is returned if it is there?

Note: My question is very similar to Retrieve only the queried element in an object array in MongoDB collection but is specific to implementing in Mongoose, not MongoDB.

Community
  • 1
  • 1
N10
  • 43
  • 5
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Blakes Seven Mar 22 '16 at 11:24
  • Of course it is exactly the same. You use `$elemMatch` in projection just as is in the first example. There is absolutely **no** difference between Mongoose and MongoDB. Mongoose is not seperate software. The query format is exactly the same because it is actually "fulfilled" by the MongoDB server. – Blakes Seven Mar 22 '16 at 11:25

0 Answers0