programing

동일한 필드의 mongo 문서를 찾는 방법

telebox 2023. 5. 2. 22:36
반응형

동일한 필드의 mongo 문서를 찾는 방법

몽고 컬렉션이 있는데, 이 컬렉션에서 필드 이름과 주소가 같은 문서를 찾아야 합니다.

제가 많이 검색해보니 MongoDb 쿼리 조건은 2개의 필드와 MongoDB: 고유하고 희소한 복합 인덱스와 희소한 값을 비교했을 뿐인데, 이러한 질문들에서 그들은 a = 필드 b의 문서를 찾고 있지만, 저는 문서 1.a == document2.a를 찾아야 합니다.

Aggregation Framework 및 를 사용하여 중복 항목을 찾을 수 있습니다.

데이터 설정 예:

// Batch insert some test data
db.mycollection.insert([
    {a:1, b:2, c:3},
    {a:1, b:2, c:4},
    {a:0, b:2, c:3},
    {a:3, b:2, c:4}
])

집계 쿼리:

db.mycollection.aggregate(
    { $group: { 
        // Group by fields to match on (a,b)
        _id: { a: "$a", b: "$b" },

        // Count number of matching docs for the group
        count: { $sum:  1 },

        // Save the _id for matching docs
        docs: { $push: "$_id" }
    }},

    // Limit results to duplicates (more than 1 match) 
    { $match: {
        count: { $gt : 1 }
    }}
)

출력 예:

{
    "result" : [
        {
            "_id" : {
                "a" : 1,
                "b" : 2
            },
            "count" : 2,
            "docs" : [
                ObjectId("5162b2e7d650a687b2154232"),
                ObjectId("5162b2e7d650a687b2154233")
            ]
        }
    ],
    "ok" : 1
}

언급URL : https://stackoverflow.com/questions/14770170/how-to-find-mongo-documents-with-a-same-field

반응형