D
D
Dmitry Filippov2018-08-07 14:23:39
MongoDB
Dmitry Filippov, 2018-08-07 14:23:39

What is the correct way to use functions in MongoDB for sql joins-like query?

There are two collections.
inventory:

> db.inventory.find().pretty()
{
        "_id" : 1,
        "sku" : "almonds",
        "description" : "product 1",
        "instock" : 120
}
{ "_id" : 2, "sku" : "bread", "description" : "product 2", "instock" : 80 }
{
        "_id" : 3,
        "sku" : "cashews",
        "description" : "product 3",
        "instock" : 60
}
{
        "_id" : 4,
        "sku" : "pecans",
        "description" : "product 4",
        "instock" : 70
}
{ "_id" : 5, "sku" : null, "description" : "Incomplete" }
{ "_id" : 6 }

And orders:
> db.orders.find().pretty()
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }
{ "_id" : 3 }

I am running the following query:
db.orders.find().forEach(
  function (newOrders) {
    newOrders.item = db.inventory.findOne({"sku": newOrders.item});
    db.ordersRealoded.insert(newOrders);
  }
)

But after that an error is thrown:
2018-08-07T14:18:10.868+0300 E QUERY    [js] Error: error: {
        "ok" : 0,
        "errmsg" : "cannot compare to undefined",
        "code" : 2,
        "codeName" : "BadValue"
} :
[email protected]/mongo/shell/utils.js:25:13
[email protected]/mongo/shell/query.js:707:1
[email protected]/mongo/shell/query.js:113:28
[email protected]/mongo/shell/query.js:287:5
[email protected]/mongo/shell/collection.js:254:10
@(shell):3:18
[email protected]/mongo/shell/query.js:500:1
@(shell):1:1

What can be the problem? It is necessary that the new collection has an item field with all the values ​​from inventory.sku.
Now I'm trying to do this on a simple example in order to deal with nested queries. I would be glad if you leave links to some Russian-language doc or tutorial on this topic.
Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question