How to return only value of a field in mongodb

后端 未结 4 1715
别跟我提以往
别跟我提以往 2020-12-17 17:48

After applying the find operation in mongodb.. i get the following list of documents..

  db.users.find(....)

i got:

 { \"t         


        
相关标签:
4条回答
  • 2020-12-17 18:10

    At first db.users.find(...).map() didn't work because db.users.find(...) doesn't return you a real array.

    So you need to convert to array at first.

    db.users.find(...).toArray()
    

    Then if you apply map() function will work

      db.users.find(...).toArray().map( function(u) { return u.text ; } )
    

    Another simple trick is using .forEach()

    This will do the trick

    var cursor = db.users.find(...); // returns cursor object which is a pointer to result set
    
    var results = [];
    cursor.forEach(
      function(row) {
         results.push(row.text);
      });
    
    results //results will contain the values
    
    0 讨论(0)
  • 2020-12-17 18:10

    Another option is simply to use distinct:

    db.users.distinct("first_name");
    

    Would return:

    [
      "John",
      "Jennifer",
      ...
    ]
    
    0 讨论(0)
  • 2020-12-17 18:11

    you can use

    var u=db.users.find({...},{text:1,_id:0})
    while(u.hasNext()){print(u.Next().text);}
    
    0 讨论(0)
  • 2020-12-17 18:19

    Not sure what you language implementation is but the basic concept is:

    var result = []
    db.users.find().forEach(function(u) { result.push(u.text) })
    

    And the returned value to result is:

    ["Hey","Hi","Hello","yes"]
    
    0 讨论(0)
提交回复
热议问题