How to write MongoDB query statement for a specific requirement? - mongodb

Here is the MongoDB document format:
{
'_id':...,
'user_id':...,
'user_info':...,
...
}
The user_info's value is a number or a string, I'd like to combine all the user_info's value into an array as the key 'user_info' 's value in the query result, like here:
{ 'user_id': ..., 'user_info': [ ..., ...] }
How to write the query statement to query data like this?

You need to use $in
The $in operator selects the documents where the value of a field equals any value in the specified array.
db.users.find({'user_info': {$in: [1, "a"]}})
Here you can read about it $in

Related

Mongodb: how to list type of a field?

I've a field in a collection where
- in 99.9% of documents it's an array
- in 00.01% is a subdocument
Can I
- LIST documents this field and a column that reports this field's type?
- and/or
- FILTER documents by the type of this field?
Yes you can, with the $type operator:
To filter:
db.someCollection.find({ "fieldThatMightBeAnArray": {$type: 4} })
For a list of types (and string aliases), see the documentation page on the query operator $type.
To list the type in a column:
You should be able to use the $type aggregation operator in an aggregation query.
db.someCollection.aggregate([{
$project: {
"fieldThatMightBeAnArray": 1,
"typeOfFieldThatMightBeAnArray" : { $type: "$fieldThatMightBeAnArray" }
}
}])
(I did not test this last one myself)

How to fetch just the "_id" field from MongoDB find()

I wish to return just the document id's from mongo that match a find() query.
I know I can pass an object to exclude or include in the result set, however I cannot find a way to just return the _id field.
My thought process is returning just this bit of information is going to be way more efficient (my use case requires no other document data just the ObjectId).
An example query that I expected to work was:
collection.find({}, { _id: 1 }).toArray(function(err, docs) {
...
}
However this returns the entire document and not just the _id field.
You just need to use a projection to find what ya want.
collection.find({filter criteria here}, {foo: 0, bar: 0, _id: 1});
Since I don't know what your document collection looks like this is all I can do for you. foo: 0 for example is exclude this property.
I found that using the cursor object directly I can specify the required projection. The mongodb package on npm when calling toArray() is returning the entire document regardless of the projection specified in the initial find(). Fixed working example below that satisfies my requirements of just getting the _id field.
Example document:
{
_id: new ObjectId(...),
test1: "hello",
test2: "world!"
}
Working Projection
var cursor = collection.find({});
cursor.project({
test1: 0,
test2: 0
});
cursor.toArray(function(err, docs) {
// Importantly the docs objects here only
// have the field _id
});
Because _id is by definition unique, you can use distinct to get an array of the _id values of all documents as:
collection.distinct('_id', function(err, ids) {
...
}
you can do like this
collection.find({},'_id').toArray(function(err, docs) {
...
}

moogoose first record from sub-document

I want to use and condition to select the first matched record from sub-document.
MongoDB:
db.users.findOne({'$and': [{username:'kevfixx'}, {'check.month':'Jan'}, {check.year': 2015}]}, {check.$': 1})
In Mongoosejs how do I put in this {check.$': 1}:
User.findOne({'$and': [{username:'kevfixx'}, {'check.month': 'Jan'}, {'check.year': 2015}]}, function(err, user){ ... }
Field selection is passed as a second parameter to findOne using a string of 'check.$', but you should also fix your query.
As it is now, this could match month against one element, and year against another. Use $elemMatch to require that both field match the same element.
And you don't need to use $and here as all query terms are implicitly AND'ed together.
Putting it all together, your Mongoose query should look like:
User.findOne(
{username: 'kevfixx', check: {$elemMatch: {month: 'Jan', year: 2015}}},
'check.$',
function (err, user) {...}
);

In MongoDB how to find all documents which are in my list of ObjectId's?

I have a list of ObjectId's _id's and I want all the documents which match these ids, is there an efficient way to find these objects in one query?
Yes there is, use the $in operator.
http://docs.mongodb.org/manual/reference/operator/query/in/#op._S_in
Example usage:
var arr = [ObjectId("52b11a1a3055376e9e00003d"), ObjectId("52b11a1a3055376e9e00003d")]
db.collection.find({_id: {$in: arr}})
The $in operator takes an array of arguments so what you want to do is supply all of your ObjectId values in a list to that:
var list = [ObjectId("53cf334bb3b0796e36d42184"),ObjectId("53cf3358b3b0796e36d42185")];
db.collection.find({ "_id": { "$in": list } })
Also see other query operators in the manual:
How about the $in operator as follows:
db.collection.find({_id: {$in : [ObjectId("505bd76785ebb509fc183733"), ObjectId("505bd76785ebb509fc183734")] }});

Query for a field in an object in array with Mongo?

Is it possible to use Mongo to query for entries that have a particular value in a field in an object in an array.
For example, let's say I want to find all objects where field1 has an array of objects, one of which has the field 'one' with a value of 1. This query should return the following object from my collection:
{_id: 0000, field1: [{one: 1, two: 2}, {one: 'uno', two: 'dos'}]}
I suppose what you need is:
db.collection.find( { field1: { $elemMatch: { one: 1 } } } );
http://docs.mongodb.org/manual/reference/operator/elemMatch/#op._S_elemMatch
This is an old question, but a simpler way to perform this query is to use dot notation:
db.collection.find({'field1.one': 1})