首页 > 解决方案 > 如何更新匹配某些 mongoDB 条件的四分之一决赛数组中的第一个对象?

问题描述

我有下面的文档,我需要遍历 QuarterFinals 数组并将我找到的第一个空地址属性更新为“123”

{
    "data": {
        "createTournament": {
            "_id": "613122d0c7befdeef3b0b571",
            "title": "Jogo de truco",
            "description": "",
            "location": "Batalha na rua",
            "type": "Battle",
            "players": [],
            "status": "PENDING",
            "size": 8,
            "entryFee": 1,
            "prizePool": 20,
            "currency": "USD",
            "startDate": "2021-09-01",
            "endDate": "2021-09-01",
            "rounds": {
                "quarterFinals": [{
                    "id": "9fb6f9ca-c06a-4972-b140-0f2425a90707",
                    "arena": "",
                    "firstParticipant": {
                        "address": null,
                        "battlesWon": 0
                    },
                    "secondParticipant": {
                        "address": null,
                        "battlesWon": 0
                    }
                }]
            }
        }
    }
}

标签: mongodbmongoose

解决方案


一种方法是

exports.updateData =  async (tournamentID,address)=>{
    return await db_collection.updateOne({id:tournamentId,rounds:{$elemMatch:{quarterfinals.address:null}}},{$push:{address:address});
};

推荐阅读