Dng
Dng

Reputation: 643

Query with double nested array of elements

I am stuck at this. I'm trying to query two levels of nested documents with the index i.e [0]. Here's my mongoDb document.

[
  {
    "_id": ObjectId("5b8803a07078906483e2e8a9"),
    "vote": [
      [
        "a4d77175-250d-4990-bc1c-d79c8175c1f0",
        "5b82e2d1b47b3513f3f25854"
      ],
      [
        "a934cf1d-ecb1-4764-b8bb-9c3c40c1128d",
        "5b82e355b47b3513f3f25858"
      ]
    ],
    "election_id": ObjectId("5b82e3cfb47b3513f3f2585a"),
    "user_id": ObjectId("5b82e2d1b47b3513f3f25854"),
    "date": "Thu Aug 30 2018 17:48:00 GMT+0300 (EAT)",
    "__v": 0
  }
]

I'm trying to get to this value "a4d77175-250d-4990-bc1c-d79c8175c1f0" inside vote. I tried this to no avail.

exports.getVotesByPosts = (req, res, next) => {
  Vote.find({'vote[0][0]': req.params.id}, (err, vote) => {
    res.json(vote);
  }).sort( { date: -1 });
}

Thanks in advance for your help. Regards

Upvotes: 1

Views: 332

Answers (2)

Dng
Dng

Reputation: 643

Here's how i fixed it using Anthony's answer

    Vote.find({
      "vote": {
        "$elemMatch": {
          "$elemMatch": {
            "$eq": req.params.id
          }
        }
      }
    });

Upvotes: 0

Ashh
Ashh

Reputation: 46451

You need to use $elemMatch query with the $eq operator

Vote.find({
  "vote": {
    "$elemMatch": {
      "$elemMatch": {
        "$eq": "a4d77175-250d-4990-bc1c-d79c8175c1f0"
      }
    }
  }
})

Upvotes: 1

Related Questions