2

I have a query db.collection('image').find({ category: "concept art"}, { projection: _id: 0, imgUrl:1 }).toArray() and have an output:

[
    {
        "imgUrl": "images\\2020-01-23T14-41-48.158Z-abandoned.jpg"
    },
    {
        "imgUrl": "images\\2020-01-25T01-45-14.880Z-pIMG_6443.jpg"
    }
]

I want an output like this:

[
"images\\2020-01-23T14-41-48.158Z-abandoned.jpg",
  "images\\2020-01-25T01-45-14.880Z-pIMG_6443.jpg"
]

Where can I find some information about this or how to achieve this?

1 Answer 1

2

You need to try aggregation for that :

db.collection.aggregate([
    /** match docs based on criteria same as find */
    { $match: { "category": "concept art" } },
    /** group all docs and push imageUrls to an array */
    { $group: { _id: '', imgUrl: { $push: '$imgUrl' } } },
    /** remove _id from final doc */
    { $project: { _id: 0 } }])

Collection Data :

/* 1 */
{
    "_id" : ObjectId("5e2bc27cdc95d08ab83819e8"),
    "category" : "concept art",
    "isImage" : true,
    "imgUrl" : "images\\2020-01-23T14-41-48.158Z-abandoned.jpg"
}

/* 2 */
{
    "_id" : ObjectId("5e2bc27cdc95d08ab83819e9"),
    "category" : "concept art",
    "isImage" : true,
    "imgUrl" : "images\\2020-01-25T01-45-14.880Z-pIMG_6443.jpg"
}

Output :

/* 1 */
{
    "imgUrl" : [ 
        "images\\2020-01-23T14-41-48.158Z-abandoned.jpg", 
        "images\\2020-01-25T01-45-14.880Z-pIMG_6443.jpg"
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

I got [ { imgUrl: [ data ] } ]. Can I get just [ data ]?
@nukuutos : It will return an array of objects or an object, So in your code you can do dbResult.imgUrl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.