mongo 쿼리 후 배열에서 mongoID의 순서를 유지하는 방법 (How to preserve the order of mongoID in an array after a mongo query)


문제 설명

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"
    }
  }
])

mongoplayground

(by PhillipYuTing)

참조 문서

  1. How to preserve the order of mongoID in an array after a mongo query (CC BY‑SA 2.5/3.0/4.0)

#Sorting #arrays #mongoDB






관련 질문

geo 및 int의 기능에 의한 스마트 정렬 (Smart sorting by function of geo and int)

문자열 삽입 정렬 프로그램 (String Insertion Sort program)

XSLT에서 계산된 값으로 정렬 (Sorting by calculated value in XSLT)

가장 가까운 휴일까지의 스파크 SQL 거리 (spark sql distance to nearest holiday)

Node.js로 대용량 파일 정렬 및 비교 (Sorting and diffing large files with Node.js)

다른 열 기준으로 날짜/시간의 순위를 매기는 R 함수가 있습니까? (Is there an R function that will rank dates/times by other column criteria?)

Java 병합 정렬의 정렬 부분 이해 (Understanding the sort part of Java Merge sort)

iterator와 ptrdiff 비교 (Comparing iterator with ptrdiff)

메모리에 로드할 수 없는 매우 큰 파일을 정렬하고 검색하는 방법은 무엇입니까? (How to sort and search in a very huge file that can't be loaded into memory?)

프로그래머가 사용하는 정렬 알고리즘은 무엇입니까? (What sorting algorithm is used by programmers?)

클래스/유형을 포함하지 않고 중첩된 defaultdict를 인쇄하는 방법은 무엇입니까? (How to print a nested defaultdict without including the class/type?)

mongo 쿼리 후 배열에서 mongoID의 순서를 유지하는 방법 (How to preserve the order of mongoID in an array after a mongo query)







코멘트