문제 설명
mongo 쿼리 후 배열에서 mongoID의 순서를 유지하는 방법 (How to preserve the order of mongoID in an array after a mongo query)
나는 mongoIds의 배열을 쿼리하고 같은 순서로 데이터를 반환하려고 하지만, 이것을 시도할 때마다 순서는 아래에 선언된 것과 같지 않습니다.
샘플 코드:
let id = [
"620d323b8d0273004c8993a4",
"620d32498d0273004c8993a5",
"61e730a745171f002d85df4b",
"620cfe708d0273004c89933a"
]
let test = await User.find({'_id': {$in: id}}, 'id text')
console.log(test)
로깅 테스트 후 출력은 다음과 같이 반환됩니다.
[
{"_id": "61e730a745171f002d85df4b"},
{"_id": "620cfe708d0273004c89933a"},
{"_id": "620d323b8d0273004c8993a4"},
{"_id": "620d32498d0273004c8993a5"}
]
이를 첫 번째 코드 조각으로 반환하고 싶습니다. 도움을 주시면 감사하겠습니다.
참조 솔루션
방법 1:
db.collection.aggregate([
{
"$match": {
_id: {
"$in": [
"620d323b8d0273004c8993a4",
"620d32498d0273004c8993a5",
"61e730a745171f002d85df4b",
"620cfe708d0273004c89933a"
]
}
}
},
{
"$group": {
"_id": null,
"docs": {
"$push": "$$ROOT"
}
}
},
{
"$set": {
"docs": {
"$map": {
"input": [
"620d323b8d0273004c8993a4",
"620d32498d0273004c8993a5",
"61e730a745171f002d85df4b",
"620cfe708d0273004c89933a"
],
"as": "s",
"in": {
"$filter": {
"input": "$docs",
"as": "d",
"cond": {
"$eq": [
"$$d._id",
"$$s"
]
}
}
}
}
}
}
},
{
"$unwind": "$docs"
},
{
"$replaceWith": {
"$first": "$docs"
}
}
])