I need to count documents unique _id with ObjectId field. My documents are like:
So, I need to count these documents by unique _id and then replace everyone using replaceOne method (without touching _id of the document, because _id field is immutable ) to another documents.
I know that I can realize it with a few ways:
1) Using Iterator of FindIterable to get the count of the documents:
FindIterable findIterable = collection.find(Filters.eq("_id" (this is field), ... (but how I need to write value here if each document has unique _id?) ));
Iterator iterator = findIterable.iterator();
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
2) or simply create variable as long count = collection.count(Document.parse("_id : (this is field) " + ...(but how I need to write value here if each document has unique _id?)));
Correct me, please, or advise me the way how can I count these documents properly by unique _id to replace then? I appreciate any help.
As mentioned by @mtj,
Ids are unique by design, so the number of unique _ids is equal to the number of documents in the collection. Or in other words: use
collection.count()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.