How to fetch only few fields from all the MongoDB records [duplicate] - mongodb

This question already has answers here:
How to select a single field for all documents in a MongoDB collection?
(24 answers)
Closed 3 years ago.
I'm new to MongoDB work and I need help in the following.
I have a collection named student in MongoDB. And I have the following data in it.
{'_id': 1, 'name': 'A', 'dt_joined': '2010'}
{'_id': 2, 'name': 'B', 'dt_joined': '2011'}
{'_id': 3, 'name': 'C', 'dt_joined': '2009'}
{'_id': 4, 'name': 'D', 'dt_joined': '2010'}
{'_id': 5, 'name': 'E', 'dt_joined': '2008'}
From the above collection, I want to retrieve (_id, dt_joined) from all the records. That means, I'm expecting the following result.
{'_id': 1, 'dt_joined': '2010'}
{'_id': 2, 'dt_joined': '2011'}
{'_id': 3, 'dt_joined': '2009'}
{'_id': 4, 'dt_joined': '2010'}
{'_id': 5, 'dt_joined': '2008'}
Is it possible with the MongoDB find command?
Thanks in advance!!

try this
db.student.find({}, {_id:1, dt_joined: 1 })
for more details check official site - https://docs.mongodb.com/manual/reference/method/db.collection.find/

You can use one of the following.
db.student.find({}, {_id:1, dt_joined: 1 })
db.student.find({}, {name: 0 })

Related

pymongo query that matches values from fields within the same document?

I am accessing MongoDB with pymongo and a document looks like this:
{'_id': ObjectId('60f1803de8984dc1414687a4'),
'match': {'season': '1',
'node': {'id': 17, 'name': 'zxc'},
'players': [{'userId': 'asdf',
'field1': 'asd',
'pings': [{'currentPing': 8,
'nodeId': 43},
{'currentPing': 8,
'nodeId': 29},
{'currentPing': 22,
'nodeId': 17}],
{'userId': 'fdsa',
'field1': 'asd',
'pings': [{'currentPing': 10,
'nodeId': 43},
{'currentPing': 50,
'nodeId': 29},
{'currentPing': 10,
'nodeId': 17}]}
I want to get the nodeId field that equals the node.id field, so far my request looks like this:
db_collection.find_one({"$and": [{"match.season": {"$eq" : 1}}, {"match.players":{"$exists": True}}]}, {'match.node.id': 1, 'match.players.ping': 1})
but I'm unsure how to query by the described condition

MongoDB - Is it possible to only insert a record when the record doesn't exist

I have a database with custom ids and I only want to insert a new record if the id is different from the other ids. If the id exists I don't want to update the value (so I think upsert isn't a solution for me).
I'm using the pymongo connector.
Example Database:
[
{"_id": 1, "name": "john"},
{"_id": 2, "name": "paul"}
]
Trap and ignore the DuplicateKeyError, e.g.:
pymongo import MongoClient
from pymongo.errors import DuplicateKeyError
db = MongoClient()['mydatabase']
records = [
{"_id": 1, "name": "john"},
{"_id": 2, "name": "paul"},
{"_id": 3, "name": "ringo"}
]
for record in records:
try:
db.mycollection.insert_one(record)
print (f'Inserted {record}')
except DuplicateKeyError:
print (f'Skipped duplicate {record}')
pass
Result (something like):
Skipped duplicate {'_id': 1, 'name': 'john'}
Skipped duplicate {'_id': 2, 'name': 'paul'}
Inserted {'_id': 3, 'name': 'ringo'}

Can I sort the values in a field in mongodb?

If I have a document like this
{'id': 123, 'keywords': {'keyword1': 3, 'keyword2': 8, 'keyword3': 2}}
Can I get a query result with keywords sorted by values, like
{'id': 123, 'keywords': {'keyword3': 2, 'keyword1': 3, 'keyword2': 8}}
Is there a built-in mongodb feature for doing this? Or I have to implement this in application level?

I want to assign fields with mongoengine?

I have the following query:
Family.objects('name': 'bob')
which returns:
{'_id': 22, 'name': 'bob', 'age': 12, 'height': 176}
But I just need age
I can do it with mongodb:
db.family.find({'name': 'bob'}, {'age': 1})
But, how can I do it with mongoengine?
What you want is the only() method.
Family.objects(name='bob').only('age')
If you use get then use . to access fields' values
Family.objects.get(name='bob').age

Mongodb: find subdocuments whose fields are in non-canonical order

As I switch to subdoc equality testing, I want to ensure all of my documents' subdocs field orders are in the canonical ordering which I will be testing. I cannot figure out a good query for checking this.
That is, given these records:
{'_id': .., 'doc':{'a': 1, 'b': 2}, ..}
{'_id': .., 'doc':{'a': 11, 'b': 21}, ..}
{'_id': .., 'doc':{'a': 0, 'b': 2}, ..}
...
{'_id': .., 'doc':{'b': 0, 'a': 4}, ..}
If I query with 'doc' : {'a': 4, 'b': 0} I won't find the doc w/ keys in the "wrong" order. I'd like to write a one-time query to find all of these docs, but even with $where I don't see how I can check the order of keys (I guess the where could try querying with the canonical order if need be).
So, I wrote a $where which does it. I'm not sure it's the best solution:
db.mycollection.find({$where: function() {
var keys = Object.keys(this['doc']);
var ref = ['a', 'b'];
for (var i=0; i < ref.length; i++) {
if (keys[i] != ref[i]) return true;
}
return false;
}},
{_id: 1})
Obviously this is overkill if my docs really only had the 2 subfields, but that's the pattern.