Let's say that I have thousands of documents in the mongodb collection. Every random document contains object ownersData with two properties (ownerId, ownerRef)
{
"_id": {....},
"name": "abc",
"ownersData": { "ownerId":"1", "ownerRef":"qwer" }
}
what should be the fastest way to query all documents with info that some document contains certain ownerRef value
CodePudding user response:
Assuming you have C# objects representing the data in your database, you could achieve this using linq.
public IEnumerable<Document>? GetDocumentByOwnerRef(string ownerReference)
=> dbContext.Documents.Where(d =>
d.ownerData is not null && d.ownersData.ownerRef.Equals(ownerReference)
).ToList();
EDIT: As @SJFJ correctly pointed out in the comments; while this does work, it will scan your entire collection, making it a very long process. Creating an index on the ownerRef
column in your mongodb will save performance and load time.