Mongo Db Manual reference

873 views Asked by At

I have an issue in manual reference. Can anyone help? I have the following two collections in 'User' database:

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"
}

Selecting address from 'myUser' collection in to result variable:

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

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

Fetch the data from myAddress collection by matching myUser collection:

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

Below is the error:

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

how to fix this issue?

1

There are 1 answers

3
Álvaro Pérez Soria On

The value returned in the find() query is a cursor, so if you print the value the cursor iterates and the value is lost. If you want to "keep" the content, then call .next() (as cdbajorin suggested) or .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" }