Say I have a collection of people:
{ _id: ObjectId(1), name: "Bob" }
{ _id: ObjectId(1), name: "Alice" }
{ _id: ObjectId(2), name: "Bob" }
{ _id: ObjectId(2), name: "Alice" }
{ _id: ObjectId(2), name: "Charlie" }
I'm simplifying ObjectId(n) to represent n
being the default timestamp mongo includes inside the ObjectId.
Now I have an application that requires fetching uniquely named people, showing only the records that was inserted the latest. So ultimately the app wants these records only:
{ _id: ObjectId(2), name: "Bob" }
{ _id: ObjectId(2), name: "Alice" }
{ _id: ObjectId(2), name: "Charlie" }
I don't want to have a unique index on name
because I actually do want to store repeated people. The uniqueness constraint comes from application business logic irrelevant to the collection.
Is there a way I can query mongo to directly get these results, or is this logic something I have to write up in my application after retrieving all records? I don't have much mongoDB experience so there might be an obvious solution I'm unaware of.