Mongo Db手册参考

时间:2016-12-22 15:46:15

标签: mongodb manual

我手动参考有问题。有人可以帮忙吗?我在' User'中有以下两个系列。数据库:

MongoDB Enterprise > db.myUser.find().pretty()
{
        "_id" : ObjectId("585beb14efb2d0abae8bcfe5"),
        "name" : "Tom Benzamin",
        "contact" : "987654321",
        "dob" : "01-01-1991",
        "address" : [
                ObjectId("58599187efb2d0abae8bcfdf"),
                ObjectId("58599187efb2d0abae8bcfe0")
        ]
}

MongoDB Enterprise > db.myAddress.find().pretty()
{
        "_id" : ObjectId("58599187efb2d0abae8bcfdf"),
        "building" : "22 A, Indiana Apt",
        "pincode" : 123456,
        "city" : "Los Angeles",
        "state" : "california"
}

从' myUser'中选择地址收集到结果变量:

MongoDB Enterprise > var result = db.myUser.find({},{_id:0,address:1})

MongoDB Enterprise > result
{ "address" : [ ObjectId("58599187efb2d0abae8bcfdf"), ObjectId("58599187efb2d0abae8bcfe0") ] }

通过匹配myUser集合从myAddress集合中获取数据:

MongoDB Enterprise > var Final = db.myAddress.find({_id:{$in:result["address"]}}
)

以下是错误:

MongoDB Enterprise > Final
Error: error: {
        "ok" : 0,
        "errmsg" : "$in needs an array",
        "code" : 2,
        "codeName" : "BadValue"
}

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

find()查询中返回的值是一个游标,因此如果您打印该值,则游标将迭代并且该值将丢失。如果你想“保留”内容,那么调用.next()(如cdbajorin建议)或.toArray()

> var result = db.myUser.find({},{_id:0,address:1}).next()

> result
    {
        "address" : [
            ObjectId("58599187efb2d0abae8bcfdf"),
            ObjectId("58599187efb2d0abae8bcfe0")
        ]
    }

>var Final = db.myAddress.find({_id:{$in:result.address}})

>Final

{ "_id" : ObjectId("58599187efb2d0abae8bcfdf"), "building" : "22 A, Indiana Apt", "pincode" : 123456, "city" : "Los Angeles", "state" : "california" }