Add data to BSON conditionally

2,771 views
Skip to first unread message

Paulo Coutinho

unread,
Jul 3, 2015, 8:20:19 PM7/3/15
to golan...@googlegroups.com
Hi,

I want add data to BSON conditionally.

Like this pseudo-code:

var conditions := {}


if (hasPost('name'))
{
    conditions  
+= bson.M{ name: post('name') }
}


if (hasPost('name'))
{
    conditions  
+= bson.M{ name: post('name') }
}


var results := findAll(conditions)



I dont know how i can add where/order/sort conditions progressively. 

Can anyone help me with this?

Matt Harden

unread,
Jul 3, 2015, 9:26:47 PM7/3/15
to Paulo Coutinho, golan...@googlegroups.com
var conditions bson.M

if hasPost('name') {
    conditions['name'] = post('name')
}
.....

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Paulo Coutinho

unread,
Jul 3, 2015, 9:43:05 PM7/3/15
to Matt Harden, golan...@googlegroups.com
No man,

I want add conditions and query parts to mgo. Like equals, $gte, sort, select, but inside each if condition.

Enviado do meu iPhone

Matt Harden

unread,
Jul 3, 2015, 10:12:15 PM7/3/15
to Paulo Coutinho, golan...@googlegroups.com
For filtering, add entries to the map:

conditions = bson.M{}
if ... {
    conditions["name"] = name
}
if ... {
    conditions["age"] = bson.M{"$gte": 15}
}

Then run Find to obtain a query

q := collection.Find(conditions)

Then you can modify the query to do sorting, selection, etc.

if ... {
    q = q.Sort("age")
}
if ... {
    q = q.Select("name", "age")
}

Paulo Coutinho

unread,
Jul 4, 2015, 12:36:33 AM7/4/15
to Matt Harden, golan...@googlegroups.com
Thanks, it worked like a charm:


Thanks.
--
Atenciosamente,
Paulo Coutinho.
Blog: blog.prsolucoes.com
Site: www.prsolucoes.com
Msn:  pa...@prsolucoes.com
Skype: paulo.prsolucoes
Telefone: +55 21 9386-0010
Consultor Certificado Bindows
Reply all
Reply to author
Forward
0 new messages