0

I have the following Schema in Mongoose and I want to make a database query on the following schema:

const History = new Schema({
  username: { type: String, index: true, unique: true },
  history: [{
    ex: { type: Number, index: true },
    date: { type: String },
    time: { type: Number },
  }],
});

I want to query for a specific username and then within that record I only want the history records where ex: 4 for example. I've been able to get a single entry back like this:

History.find({ username: 'testuser', 'history.ex': 4 }, { 'history.$': 1 }, callback);

In other words. I want to retrieve a single document of which its attribute array history is only a selection of all its history items, as I want to only have objects from that array which have e.g. ex:4.

Ansjovis86
  • 1,506
  • 5
  • 17
  • 48
  • This is a different question as I'm also querying a specific document, whereas in the suggested duplicated question there's is only interest for the array items. – Ansjovis86 Oct 31 '17 at 23:15
  • Ok fixed it like this: `History.aggregate({ $match: { username: 'testuser' } }, { $unwind: '$history' }, { $match: { 'history.ex': 4) } }, { $project: { username: 1, history: { ex: 1, date: 1 } } }, callback);` – Ansjovis86 Nov 01 '17 at 02:55

0 Answers0