1

I have a document like this.

{ "_id" : ObjectId("5c6cc08a568f4cdf7870b3a7"),

"phone" : { "cell" : [ "854-6574-545", "545-6456-545" ], "home" : [ "5474-647-574", "455-6878-758" ] } }

I want to display output like this. output

{
        "_id" : ObjectId("5c6cc08a568f4cdf7870b3a7"),
        "phone" : {
                "cell" : [
                        "854-6574-545"
                         ]
        }
}

please advice.

1 Answer 1

2

Use $slice to project number from array.

Query:

db.collection.find({},
{
  "phone.cell": {
    $slice: 1
  },
  "phone.home": 0
})

Result:

{
    "_id": ObjectId("5c6cc08a568f4cdf7870b3a7"),
    "phone": {
      "cell": [
        "854-6574-545"
      ]
    }
  }

Query 2:

db.collection.find({},
    {
      "_id": 0,
      "phone.cell": {
        $slice: 1
      },
      "phone.home": 0
    })

Result 2: {

    "phone": {
      "cell": [
        "854-6574-545"
      ]
    }
  }

** Final Query - using aggregate**

db.collections.aggregate([{'$match':{'phone.cell':{'$exists':true}}},
{'$project':{'_id':1,'phone.cell':{$slice:['$phone.cell',1,1]}}}])

** Output **

{
    "_id" : ObjectId("5c6cc08a568f4cdf7870b3a7"),
    "phone" : {
        "cell" : [ 
            "545-6456-545"
        ]
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Error: error: { "ok" : 0, "errmsg" : "Projection cannot have a mix of inclusion and exclusion.", "code" : 2, "codeName" : "BadValue" } This is the error i am getting. we cannot include both include and exclude for same output field.
are you using mongo shell? if yes, what's the version? specify if other. I've tested this with mongo shell version 4.0.4
can you post the query that you're running?
succes query db.loandetails.find({},{'_id':0,'phone.cell':{$slice:1}, "phone.home":0}).pretty() error query db.loandetails.find({},{'_id':1,'phone.cell':{$slice:1}, "phone.home":0}).pretty() also if the collection has other fields which also gets displayed even though i dont specify in project
_id will be returned by default. No need to pass it explicitly
|

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.