准备工作:首先在maxh数据库的address集合中先插入数据
> db.address.insert({child_address:"gansu"})
WriteResult({ "nInserted" : 1 })
> db.address.insert({child_address:"lanzhou"})
WriteResult({ "nInserted" : 1 })
> db.address.find().pretty()
{ "_id" : ObjectId("5695c6395e085ed70afdd224"), "child_address" : "gansu" }
{ "_id" : ObjectId("5695c67b5e085ed70afdd225"), "child_address" : "lanzhou" }
然后将address的"_id"字段更新到user集合的name:"admin"记录中
> db.user.update({name:"admin"},{$set:{address_id:[ObjectId("5695c6395e085ed70af
dd224"),ObjectId("5695c67b5e085ed70afdd225")]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> var result = db.user.find({"name":"admin"},{"address_id":1}).pretty()
> var addresses = db.address.find({"_id":{"$in":result["address_id"]}}).pretty()
> addresses
Error: error: {
"waitedMS" : NumberLong(0),
"ok" : 0,
"errmsg" : "$in needs an array",
"code" : 2
}错误原因:findOne()写成了find()
--------------------------------------------------------------------------------------------------------
> var result = db.user.findOne({"name":"admin"},{"address_id":1}).pretty()
2016-01-13T12:00:23.633+0800 E QUERY [thread1] TypeError: db.user.findOne(...
).pretty is not a function :
@(shell):1:18错误原因:findOne()后边好像不能使用pretty()
--------------------------------------------------------------------------------------------------------
> var result = db.user.findOne({"name":"admin"},{"address_id":1})
> result
{
"_id" : ObjectId("56946fba3a18f4867aecbcd1"),
"address_id" : [
ObjectId("5695c6395e085ed70afdd224"),
ObjectId("5695c67b5e085ed70afdd225")
]
}
> var result = db.user.findOne({"name":"admin"},{"address_id":1})这个1是什么?think,think -1也可以
> var addresses = db.address.find({"_id":{"$in":result["address_id"]}}).pretty()
> addresses
{ "_id" : ObjectId("5695c6395e085ed70afdd224"), "child_address" : "gansu" }
{ "_id" : ObjectId("5695c67b5e085ed70afdd225"), "child_address" : "lanzhou" }
>
> var result = db.user.findOne({"name":"admin"},{"address_id":-1})
> var addresses = db.address.find({"_id":{"$in":result["address_id"]}}).pretty()
> addresses
{ "_id" : ObjectId("5695c6395e085ed70afdd224"), "child_address" : "gansu" }
{ "_id" : ObjectId("5695c67b5e085ed70afdd225"), "child_address" : "lanzhou" }