【问题标题】:How do I get an object from this tree in mongoDb?如何从 mongoDb 中的这棵树中获取对象?
【发布时间】:2017-04-06 13:38:58
【问题描述】:

如何从这棵树中获取对象? :

{
    "_id" : ObjectId("33b97aa654bce61322002559"),
    "name" : "Test",
    "children" : [
        "_id" : ObjectId("44b97aa654bce61322002559"),
        "name" : "Test Children",
        "children" : [
            "_id" : ObjectId("55b97aa654bce61322002559"),
            "name" : "Test Children Children",
            "children" : "",
            "products" : [
                "_id" : ObjectId("55b97aa654bce61322002559"),
                "name" : "Product 1" //I need this object
                "attrib" : [
                    "sale" : 1,
                    "new" : 1,
                    "instock" : 1,
                ]
            ],
            "products" : ""
        ]
    ],
    "products" : ""
}

级别可以是任意数字。

  • 孩子们
  • -儿童
  • --儿童
  • ---孩子们
  • ----孩子们

    $arr = Categories::findOne(['_id' => '55b97aa654bce61322002559']); 调试($arr);

也许我没有正确塑造结构数据库? 谢谢。

【问题讨论】:

  • 这是 JSON 对吧?
  • 是的,这是 JSON
  • 这看起来像 MongoDB 输出?查看数据,我认为 SQL 可能更合适。如果这不可能,您可以考虑创建 2 个集合:1 个仅存储产品,另一个将此层次结构存储为嵌套的 _ids。
  • 但是mongodb不是专门用来存储这些数据的吗?

标签: php mongodb mongodb-query


【解决方案1】:
//return an array of objects according to key, value, or key and value matching
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
            objects.push(obj);
        } else if (obj[i] == val && key == ''){
            //only add if the object is not already in the array
            if (objects.lastIndexOf(obj) == -1){
                objects.push(obj);
            }
        }
    }
    return objects;
}

【讨论】:

    猜你喜欢
    • 2013-09-19
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多