1

I'm new to MongoDB/Mongoose, I'm trying to find all documents that their usersInvited array contains a certain UID.

Example: a search through this collection with UID=123 should return id1, id2

[
  {
    "_id": "id1",
    "usersInvited": [
      {
        "UID": "123"
      }
    ]
  },
  {
    "_id": "id2",
    "usersInvited": [
      {
        "UID": "123"
      }
    ]
  },
  {
    "_id": "id3",
    "usersInvited": [
      {
        "UID": "abc"
      }
    ]
  }
]
0

3 Answers 3

2

You can use $elemMatch for this:

db.myCollection.find({
  usersInvited: {
    $elemMatch: {
      UID: "123"
    }
  }
})

https://docs.mongodb.org/v3.0/reference/method/db.collection.find/#query-an-array-of-documents

Sign up to request clarification or add additional context in comments.

Comments

2

You can directly query against the UID field within the usersInvited array elements using dot notation:

MyModel.find({'usersInvited.UID': '123'}, (err, docs) => {...});

If any of the elements of the array has a UID value of '123', the document will be included.

1 Comment

@bubakazouba: You'd replace '123' with { '$oid': '123' }, though I don't use Mongo and just read the docs.
1
var query = FriendHittups.find({
  usersInvited: {
    $elemMatch: {
      "UID": "123"
    }
  }
});

query.exec(function (err, results){

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.