skip to Main Content

I am trying to retrieve some documents from a MongoDB collection (called expenses).

Here you are the entire database, obtained using db.expenses.find():

[
  {
    _id: ObjectId("65708c6237b62067296a398f"),
    date: '2013-10-21T13:28:06.419z',
    description: 'playstation',
    category: 'miscellaneous',
    cost: 499,
    users: [ { username: 'Giacomo', amount: 499 } ]
  },
  {
    _id: ObjectId("6570950cecb7eb1b4b868409"),
    date: '2013-10-21T13:28:06.419z',
    description: 'tennis court',
    category: 'sport',
    cost: 100,
    users: [
      { username: 'prova', amount: 50 },
      { username: 'Giacomo', amount: 50 }
    ]
  },
  {
    _id: ObjectId("6570953aecb7eb1b4b86840a"),
    date: '2013-10-21T13:28:06.419z',
    description: 'netflix subscription',
    category: 'entertainment',
    cost: 100,
    users: [ { username: 'prova', amount: 10 } ]
  }
]

I need to retrieve just the documents that have an object with username: 'Giacomo' inside of the array users.

For instance, in this case, the retrieved documents should be the first and the second (the third has not username: 'Giacomo' in the array).

My problem is that I cannot find the right query for obtaining such a result.

Thank you in advance for your time and patience.

2

Answers


  1. Use $elemMatch for this target:

        db.collection.aggregate({
          "$match": {
            "users": {
              $elemMatch: {
                username: "Giacomo"
              }
            }
          }
        })
    

    See playground.

    Login or Signup to reply.
  2. This can be achieved with a simple find():

    db.expenses.find({'users.username': 'Giacomo'});
    

    See Specify a Query Condition on a Field in an Array of Document using dot notation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search