【问题标题】:Find a document in a loop在循环中查找文档
【发布时间】:2015-08-13 20:50:35
【问题描述】:

我对mongodb比较陌生,请耐心等待。假设我的收藏中有以下文档:

{_id:"3",name:'three',parentId:"2.1"}, 
{_id:"2.1",name:'two1',parentId:"1"},
{_id:"2.2",name:'two2',parentId:"1"}, 
{_id:"1",name:'one'}

我有一个db.mycoll.find({name:"three"}),它返回了 _id 3 的文档。我需要根据这个查找文档的 _id 1。

基本上,这表示类似于文件夹结构的东西。所以顶层是'one',它有'two1'和'two2'。 'two1' 又具有'three'。拥有“三”的 id 我需要得到它的顶级父级。有没有办法在 mongo 中做到这一点,还是我必须将结果返回给客户端,在那里处理它们并为每次迭代调用 mongo?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    这对我有用:

      ...find().forEach(
            function getParent(itemId) {
                var sub = db.mycoll.findOne({_id: itemId});
                if(sub) {
                    if(sub.parentId) {
                        getParent(sub.parentId)
                    } 
                    else /*top level*/
                        print(sub.name)
                }
            }
        )
    

    希望对其他人有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 2012-05-03
      • 2019-09-05
      相关资源
      最近更新 更多