when i tried : db.inventory.find({item:“postcard”}, {_id:0, instock:{$slice:1}})
returned:
i think it should return instock element 0 only
when i tried : db.inventory.find({item:“postcard”}, {_id:0, instock:{$slice:1}})
returned:
i think it should return instock element 0 only
Thanks for finding and reporting it! You’re making MongoDB better for everyone Here are the steps for reporting bug for MongoDB projects: Submit Bug Reports · mongodb/mongo Wiki · GitHub
Hi @kuku_super,
I don’t see a bug here.
Collection:
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 } ] }
]);
The first element of the array instock
is { warehouse: "B", qty: 15 }
for the postcard.
When you use this query:
> db.inventory.find({"item":"postcard"}, {_id:0, instock:{$slice:1}})
{ "item" : "postcard", "status" : "A", "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "instock" : [ { "warehouse" : "B", "qty" : 15 } ] }
You get that same first element of the array so the result looks good to me. You also get status and size because you never specified anything for them. The _id
has a special treatment in the projection so you never chose “inclusion” or “exclusion” anywhere in the projection here so the fields are included by default.
But if you run:
> db.inventory.find({"item":"postcard"}, {_id:1, instock:{$slice:1}})
{ "_id" : ObjectId("6048f80bb8352c2198e23bb8"), "instock" : [ { "warehouse" : "B", "qty" : 15 } ] }
Then it’s different because you have explicitly said that you wanted _id
and not the other fields not mentioned so you only get _id
and instock
.
If you only want instock
, you will have to do:
> db.inventory.find({"item":"postcard"}, {_id:0, status:0, size:0, item:0, instock:{$slice:1}})
{ "instock" : [ { "warehouse" : "B", "qty" : 15 } ] }
I’m surprised that the instock:{$slice:1}
doesn’t trigger the “inclusion” though and removes automatically all the other fields except _id
. That’s what I would have expected to be honest.
Cheers,
Maxime.
thx, @MaBeuLux88
if instock:{$slice:1} followed the inclusion would make the inclusion and exclusion mechanism much better.
that gave any other field a 0 to get a array element inclusion was a ugly way.
so i suggest to fix it
I agree that this would be more logical. But maybe there is a deeper reason that I ignore.
Please open a ticket and link it back here so we will have an official answer from the query team.