Reputation: 642
I want to write a mongo statement which is equivalent to this SQL statement. I know how to grab all the columns from table, but not sure how to get a column with static value out. Here is query:
select a.* , "static_value1" from table_a a;
Upvotes: 2
Views: 601
Reputation: 6404
Give a try to the following one by using aggregate
and literal
:
Let's say we have the following input:
db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
And I want as a custom result something like this:
{ "_id" : ObjectId("5c6b7e7449a55d3136613f90"), "myCustomField" : true }
To achieve the custom field, which is myCustomField
in this example:
db.inventory.aggregate([ { $project: { myCustomField: { $eq: ["$status", { $literal: "A" }] }} }]);
If you do not want to have calculated fields, simply use the following expression:
db.inventory.aggregate([ { $project: { myCustomField: { $literal: "apple" } } }]);
Which results as:
{ "_id" : ObjectId("5c6b7e7449a55d3136613f8c"), "myCustomField" : "apple" }
Doc: $literal
Upvotes: 2