简体   繁体   中英

mongodb: transform document structure to set an array into single element

Unfortunatly I have an error in some documents. Some category data is stored as an array. This isn't necessary as there is always just one category.

So how can I check if there are documents in a collction with this structure:

{
    "_id" : "q9q2He72qve62mr10",
    "category" : [
        {
            "element" : "Anything"
        }
    ],
    "order" : 1
}

... and transform it into this:

{
    "_id" : "q9q2He72qve62mr10",
    "category" : "Anything",
    "order" : 1
}

Does this work?

var data = [{
    "_id": "1",
    "category": [{
        "element": "In Array"
    }],
    "order": 1
}, {
    "_id": "2",
    "category": "Single Item",
    "order": 1
}];

console.table(data);

data.forEach(function(v) {
    if (typeof v.category === 'object' && typeof v.category.length === 'number') {
        v.category = v.category[0].element;
    }
});

console.table(data);

Before forEach loop: 在此处输入图片说明

After loop: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM