Return only array value in mongo projection

后端 未结 1 1804
孤街浪徒
孤街浪徒 2021-01-05 14:24

Is there a way to return only the value of a property in a mongodb projection? For instance, I have a document that has a property whose value is an array. I want the retu

相关标签:
1条回答
  • 2021-01-05 14:59

    JSON doesn't allow the toplevel to be an array so a normal query doesn't allow this. You can however do this with the aggregation framework:

    > db.test.remove();
    > db.test.insert({ name: "Andrew", attributes: [ { title: "Happy"}, { title: "Sad" } ] });
    > foo = db.test.aggregate( { $match: { name: "Andrew" } }, { $unwind: "$attributes" }, { $project: { _id: 0, title: "$attributes.title" } } );
    {
        "result" : [
            {
                "title" : "Happy"
            },
            {
                "title" : "Sad"
            }
        ],
        "ok" : 1
    }
    > foo.result
    [ { "title" : "Happy" }, { "title" : "Sad" } ]
    

    This however, does not create a cursor object that find does.

    0 讨论(0)
提交回复
热议问题