1

Update:

I want to only return all documents that fit four characters of a given username that is entered. So if I have a list of usernames and I type in mango3333, all usernames that are starting with "mang" should be returned. I used a regexp for that, and now I want to only return for example the username and the id of that document and not all fields, but it returns all fields.

An example document looks like this:

{"_id":{"$oid":"5d75299b0d01830"}, 
"User": 
{ "username":"mango",
  "userid":"8b8d25d3-3fe6-4d1c",
  "token":"token",
  "pw":"password",
  "statusmessage":"",
  "lastlogin":{"$date":{"$numberLong":"1567959451354"}},
  "registered":{"$date":{"$numberLong":"1567959451354"}
}

This is my query:

const db = dbClient.db(dbName);
const regexp = new RegExp(username, "gi");
db.collection(collectionName).find({ "User.Username": regexp }, { "User.Username": 1, "User.UserID": 1, "User.Statusmessage": 1 })
.toArray()
.then(result => {
  console.log(result);
})
.catch(err => console.error(`Failed to get results: ${err}`));

What am I doing wrong?

Benny
  • 839
  • 16
  • 32
  • 1
    This is about how to define a regex in a mongdb query, that part works fine for me, my issue is about returning only specific fields from a document instead of all fields – Benny Sep 10 '19 at 22:06
  • 1
    And just how do you suppose OP can supply a reproducible example? @JohnnyHK Is the code snippet not good enough? Anywho, [you can try something like this](https://stackoverflow.com/a/48610702/10431732) as it worked for that person (who was having the same issue as you)... – Matt Oestreich Sep 10 '19 at 22:28
  • @MattOestreich this solution works, thank you! – Benny Sep 10 '19 at 22:46

1 Answers1

6

The 2nd portion of the find method is an options object, not just projection. The projection portion of the query will need to be specified in this options object. Try the following:

db.collection(collectionName).find(
  { "User.Username": regexp }, 
  { 
     projection: { 
       "User.Username": 1, 
       "User.UserID": 1, 
       "User.Statusmessage": 1 
     }
  }
)
.toArray()
.then(result => {
  console.log(result);
})

See https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#find

Adam Harrison
  • 3,323
  • 2
  • 17
  • 25