How to filter only unique id documents?

Documents

{
	"_id" : ObjectId("6364ee0b94521b3d7ec62cd0"),
	"groupId" : ObjectId("61a7c52f97d24b6a5eb75252"),
	"insertedAt" : "2022-11-04T10:48:43.670370Z",
	"isActive" : false,
	"likes" : 0,
	"text" : "Hh",
	"title" : "Hh",
	"type" : "groupPost",
	"uniquePostId" : "123",
	"updatedAt" : "2022-11-04T10:48:43.670403Z",
	"userId" : ObjectId("61e1160c97d24b2673d7f136")
}
{
	"_id" : ObjectId("6364eab794521b3d7efad66d"),
	"groupId" : ObjectId("61a7c52f97d24b6a5eb75252"),
	"insertedAt" : "2022-11-04T10:34:31.935725Z",
	"isActive" : false,
	"likes" : 0,
	"teamId" : ObjectId("61e13b4e97d24b4901a923e2"),
	"text" : "7y",
	"title" : "Uyy",
	"type" : "teamPost",
	"uniquePostId" : "123",
	"updatedAt" : "2022-11-04T10:34:31.935756Z",
	"userId" : ObjectId("61e1160c97d24b2673d7f136")
}
{
	"_id" : ObjectId("6364eab794521b3d7efad66b"),
	"groupId" : ObjectId("61a7c52f97d24b6a5eb75252"),
	"insertedAt" : "2022-11-04T10:34:31.935725Z",
	"isActive" : false,
	"likes" : 0,
	"text" : "7y",
	"title" : "Uyy",
	"type" : "groupPost",
	"uniquePostId" : "456",
	"updatedAt" : "2022-11-04T10:34:31.935756Z",
	"userId" : ObjectId("61e1160c97d24b2673d7f136")
}

uniquPostId “123” is repeated I just want to get the documents only once. If I use distinct() in the query I’m getting only distinct values in the array, not the entire document, is there any way to get entire documents

db.posts.distinct("uniquePostId",{})

output
[
“123”,
“456”
]
I want the entire document not only the values

We need closure in your other posts. Share the solution you found or mark one of the post as the solution.

when you stored many documents with that field having the same value, you violated your condition of uniqueness. now you need to decide what makes the documents you want back to be unique among others with the same value.
without this decision, it is hard to make a query. so please make one. (newest, oldest, likes, date, etc.). then the rest would possibly follow an aggregation of “distinct, lookup, sort, limit 1, unwind”. sorting is impossible without criteria.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.