0
{
  A: 1
  B: null
}

vs

{
  A: 1
}

Is there any differences between the 2 documents?

  • yes its not the same, those documents are not equal also. but people use both, one difference as far as i know is that if we index the B field, we can find the documents with B=null fast, the second needs exists false and i think cant be indexed to retrieve it fast . So if you care about indexing the B and find those that have missing B i think its best to use the first one, but i am not sure – Takis Nov 12 '22 at 17:59

1 Answers1

1

Of course there is a difference. Document with B: null consumes little more space on your disk. Also if you like to query them, they are different, see Or with If and In mongodb

Comment from @Takis is not fully correct. When you create an index in MongoDB, then it indexes also documents where the field does not exist - unless you define a Sparse Index/Partial Index. This behavior is different to most relational SQL databases.

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110