Ask Your Question
2

How can additional fields that have been transformed be queried in MongoDB?

asked 2022-07-22 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-03-12 03:00:00 +0000

plato gravatar image

Additional fields that have been transformed can be queried in MongoDB using the $project operator.

The $project operator is used to specify the fields to be returned in the query result. It can also be used to rename, transform, or add new fields to the result.

Here is an example:

Suppose we have a collection called "users" with documents that look like this:

{
  "_id": ObjectId("6072b11a8ebb614a21a747c0"),
  "name": "John Smith",
  "age": 35,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY"
  }
}

If we want to add a new field called "full_address" that concatenates the street, city, and state fields, we can use the following query:

db.users.aggregate([
  {
    $project: {
      name: 1,
      age: 1,
      full_address: { $concat: [ "$address.street", ", ", "$address.city", ", ", "$address.state" ] }
    }
  }
])

The result will look like this:

{
  "_id": ObjectId("6072b11a8ebb614a21a747c0"),
  "name": "John Smith",
  "age": 35,
  "full_address": "123 Main St, New York, NY"
}

In this example, we use the $project operator to specify the fields "name", "age", and "fulladdress" to be returned in the result. We also use the $concat operator to concatenate the "address.street", "address.city", and "address.state" fields into a new field called "fulladdress".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-22 11:00:00 +0000

Seen: 15 times

Last updated: Mar 12 '22