簡體   English   中英

通過在同一文檔中定義的位置獲取數組元素作為mongoDB中的不同字段

[英]Get an array element by position defined in same document as different field in mongoDB

是否有任何簡單的方法來獲取數組元素的位置。 在同一文檔中將位置定義為不同字段的位置。

范例文件:

{
    _id:"123",
    "elementPosition": 3,
    "users": [
              {
                "username": "abcd"
              },
              {
                "username": "qweqw"
              },
              {
                "username": "fdsfsd"
              },
              {
                "username": "dsfvd"
              }
    ]

}

此外,如果有一些簡單的方法,那么還想以有效的方式進行以下操作:

  1. 更新文檔,其中users.elementPosition.username =“ abcd”並更新“ users.elementPosition.username” =“ wxyz”

*** elementPosition來自同一文檔。

我嘗試了很多方法。 其中之一是get get elementPosition,然后使用該elementPosition檢查文檔是否匹配。 但這又臟又長。

試圖在單個查詢"user."+elementPosition+".username"中將elementPosition用作變量,但無效。

還嘗試了不同的匯總查詢方式,但未獲得良好的結果。 $elementPosition投影到下一階段,並使用它來檢索特定的位置文檔,但沒有得到我想要的。

使用$ arrayElemAt運算符

    db.collection.aggregate(
    {$match : {_id: "123"} },
    {$project : {username: {$arrayElemAt: [ "$users.username", "$elementPosition" ]}}})

要解決后續問題,即您希望使用同一文檔中定義的位置將username = "abcd"的文檔更新為"wxyz" ,則可以使用bulkWrite()方法有效地執行更新。 下面顯示了如何使用MongoDB 3.2或更高版本進行處理:

var bulkUpdateOperations = [],
    counter = 0,
    setObj = {};

db.collection.find({ 
    "users.username": "abcd",
    "elementPosition": { "$exists": true }
}).forEach(function(doc) {  
    setObj["users."+ doc.elementPosition +".username"] = "wxyz";
    bulkUpdateOperations.push({
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": setObj }
        }
    });

    if (counter % 1000 == 0) {
        db.collection.bulkWrite(bulkUpdateOperations);
        bulkUpdateOperations = [];
    }
})

if (counter % 1000 != 0) { db.collection.bulkWrite(bulkUpdateOperations); }

如果使用的是MongoDB的舊版本(即v2.6或3.0),請使用這些版本支持的Bulk Operations API

var bulk = [],
    counter = 0,
    setObj = {};

db.collection.find({ 
    "users.username": "abcd",
    "elementPosition": { "$exists": true }
}).forEach(function(doc) {  
    setObj["users."+ doc.elementPosition +".username"] = "wxyz";
    bulk.find({ "_id": doc._id }).updateOne({ "$set": setObj });

    if (counter % 1000 == 0) {
        bulk.execute();
        bulk = db.collection.initializeUnorderedBulkOp();
    }
});

if (counter % 1000 != 0) { bulk.execute(); };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM