I have created a collection and added an index key by grouping 4 fields as unique.
Here are the example of field and value.
"username":string,
"companyID": ObjectID,
"areaCode": string,
"lotNum":string
The companyID's ObjectID, I'm getting it from another collection's document ID as it's ID.
I tried to insert through MongoDB .Net driver and encountered some problem.
Company company = new Company()
{
CompanyName = "xyz"
};
await _company.InsertOneAsync(company); //_company is IMongoCollection object
SomeClass someClass = new SomeClass()
{
UserName = "James",
CompanyID = company.ID, //This is the ObjectID generated by MongoDB
AreaCode = "ABC",
LotNum = "1234a"
};
await _someClass.InsertOneAsync(company); //_someClass is IMongoCollection object
So, the document object in MongoDB will look like below. I can actually view the document using Compass.
_id:ObjectID("5b062d5be75ed035f057bf06")
username:"James",
companyID: ObjectID("5b062d5be75ed035f057bf05"),
areaCode: "ABC",
lotNum:"1234a"
Now the problem is when I tried to find the document in SomeClass collection with {companyID:ObjectID("5b062d5be75ed035f057bf05")}
, I'm unable to find it.
But if I use {companyID:null}
. It's returning the document.
And I'm not able to add any new document with same username,areaCode and lotNum with a different companyID, "as duplicate key error collection" occurs eventhou the ID is from a newly created Company object have brand new ID. MongoDB is still saying it is NULL.
Am I doing something wrong? How can I fixed this problem.
Here are my data object for Company and SomeClass
public class Company
{
public ObjectId Id { get; set; }
public string CompanyName{ get; set;}
}
public class SomeClass
{
public ObjectId Id { get; set; }
public string UserName { get; set;}
[BsonRepresentation(BsonType.ObjectId)]
public string CompanyID { get; set; }
public string AreaCode{ get; set; }
public string LotNum{ get; set; }
}
As mentioned by Alex Blex in the comments under my question, it is due to case sensitivity. Here's his answer:
It's case sensitive.
"companyID" != "CompanyID"
. BasicallycompanyID
is undefined in any of your documents so all of them match criteriacompanyID:null