如何在MongoDb对象数组中查找文档?

c3frrgcw  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(139)

I Have document like this.

{
accountId: "182092109",
documents:[{
idDocuments:"0000",
filePath :"/data/photo/1.png",
status:"EXIST"
},
{
idDocuments:"0001",
filePath :"/data/photo/2.png",
status:"EXIST"
}]
}

but i need document to be like

{
idDocuments:"0001",
filePath :"/data/photo/2.png",
status:"EXIST"
}]
}

is it possible ? or is this have alternative to findOne document in mongo into like that ? Thank's in Advance

3zwtqj6y

3zwtqj6y1#

据我所知,你想在一个对象数组中找到一个特定的文档。你可以在find()方法中使用$elemMatch操作。返回只匹配的结果。
您可以尝试以下操作:

db.collection.find({
    arrayOfObjects: {
        $elemMatch: {    // Finding only the ones that match
            idDocuments:"0001",
            filePath :"/data/photo/2.png",
            status:"EXIST"
        }
    }
})

如果$elemMatch返回多个结果,则可以使用$limit运算符限制find()方法。

db.collection.find({
    arrayOfObjects: {
        $elemMatch: {    // Finding only the ones that match
            idDocuments:"0001",
            filePath :"/data/photo/2.png",
            status:"EXIST"
        }
    }

}, {
    arrayOfObjects: {
        $limit: 1    // Limiting results
    }
})

大部分信息可以在MongoDB Manual中找到。
或者你可以阅读更多的here

相关问题